How does Spring annotation @Autowired work?
Solution 1:
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:
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:
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 uses the CGLib API to provide autowired dependency injection.
References
- Usage of CGLib forum comment by Rod Johnson
- 3.3.1. Injecting dependencies
- Pro Spring - Analyzing Spring Dependencies
Further Reading
- Introduction to the Spring Framework by Rod Johnson