How does Spring annotation @Autowired work?

SpringDependency InjectionAutowired

Spring Problem Overview


I came across an example of @Autowired:

public class EmpManager {
   @Autowired
   private EmpDao empDao;
}

I was curious about how the empDao get sets since there are no setter methods and it is private.

Spring Solutions


Solution 1 - Spring

Java allows access controls on a field or method to be turned off (yes, there's a security check to pass first) via the AccessibleObject.setAccessible() method which is part of the reflection framework (both Field and Method inherit from AccessibleObject). Once the field can be discovered and written to, it's pretty trivial to do the rest of it; merely a Simple Matter Of Programming.

Solution 2 - Spring

Java allows you to interact with private members of a class via reflection.

Check out ReflectionTestUtils, which is very handy for writing unit tests.

Solution 3 - Spring

No need for any setter, you just have to declare the EmpDao class with the annotation @component in order that Spring identifies it as part of the components which are contained in the ApplicationContext ...

You have 2 solutions:

  • To manually declare your beans in the XML file applicationContext :
<bean class="package.EmpDao" />
  • To use automatic detection by seeting these lines in your context file:
<context:component-scan base-package="package" />
<context:annotation-config />

AND to use the spring annotation to declare the classes that your spring container will manage as components:

@Component
class EmpDao {...}

AND to annotate its reference by @Autowired:

@Component (or @Controller, or @Service...)
class myClass {

// tells the application context to inject an instance of EmpDao here
@Autowired
EmpDao empDao;


public void useMyDao()
{
    empDao.method();
}
...
}

Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context.

Spring knows the existence of the beans EmpDao and MyClass and will instantiate automatically an instance of EmpDao in MyClass.

Solution 4 - Spring

Spring uses the CGLib API to provide autowired dependency injection.


References

Further Reading

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnthonyView Question on Stackoverflow
Solution 1 - SpringDonal FellowsView Answer on Stackoverflow
Solution 2 - SpringearldouglasView Answer on Stackoverflow
Solution 3 - SpringMrJavaJEEView Answer on Stackoverflow
Solution 4 - SpringkrockView Answer on Stackoverflow