Spring中@Autowired是如何实现的

How is @Autowired implemented in Spring

我真的很想对@autowired 有一个基本的了解 在 Spring.
中实施 反射应该以某种方式隐含在它的实现中,但我不知道如何。
你能帮我吗 ?

通过 @Autowired 的自动装配由 BeanPostProcessor 实现执行,特别是 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.

这个 BeanPostProcessor 处理每个 bean,将扫描它的 class(和 superclasses)是否有任何 @Autowired 注释,并且,取决于什么是注释(构造函数、字段或方法),它将采取适当的操作。

对于构造函数

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.

对于字段

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.

对于方法

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.

这一切都是通过反射完成的。

延伸阅读:

  • How do I invoke a Java method when given the method name as a string?
  • Is it possible in Java to access private fields via reflection