Reputation: 2894
I would really like to have even a basic understanding of how is @autowired
implemented in Spring.
Reflection should be somehow implied in its implementation, but I cannot figure out how.
Can you help ?
Upvotes: 4
Views: 1503
Reputation: 280148
Autowiring through @Autowired
is performed by a BeanPostProcessor
implementation, specifically org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
.
This BeanPostProcessor
processes every bean, will scan its class (and superclasses) for any @Autowired
annotations, and, depending on what is annotation (a constructor, field, or method), it will take appropriate action.
For constructors
Only one constructor (at max) of any given bean class may carry this annotation with the 'required' parameter set to true, indicating the constructor to autowire when used as a Spring bean. If multiple non-required constructors carry the annotation, they will be considered as candidates for autowiring. The constructor with the greatest number of dependencies that can be satisfied by matching beans in the Spring container will be chosen. If none of the candidates can be satisfied, then a default constructor (if present) will be used. An annotated constructor does not have to be public.
For fields
Fields are injected right after construction of a bean, before any config methods are invoked. Such a config field does not have to be public.
For methods
Config methods may have an arbitrary name and any number of arguments; each of those arguments will be autowired with a matching bean in the Spring container. Bean property setter methods are effectively just a special case of such a general config method. Config methods do not have to be public.
All of this is done through reflection.
Further reading:
Upvotes: 8