Spring框架里注解@Autowired的工作原理

Posted JerryWangSAP

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring框架里注解@Autowired的工作原理相关的知识,希望对你有一定的参考价值。

Suppose I have a bean named HelloWorld which has a member attribute points to another bean User.

技术图片

With annotation @Autowired, as long as getBean is called in the runtime, the returned HelloWorld instance will automatically have user attribute injected with User instance.

技术图片

How is this behavior implemented by Spring framework?

(1) in Spring container implementation’s refresh method, all singleton beans will be initialized by default.

技术图片

When the HelloWorld bean is initialized:

技术图片

Since it has the following source code:

@Autowired
private User user;

In the runtime, this annotation is available in metadata via reflection. In metadata structure below, the targetClass points to HelloWorld bean, and injectedElements points to the User class to be injected.

技术图片
技术图片

(2) In doResolveDependency, the definition for User bean is searched based on this.beanDefinitionNames ( list in DefaultListableBeanFactory ):

技术图片

Once found, the found result is added to array candidateNames:

技术图片

Then the constructor of User bean class is called ( still triggered by getBean call ), the user instance is created by calling constructor:

The created user instance together with its name “user” is inserted to the map matchingBeans.

  1. Finally the user reference is set to user attribute of HelloWorld instance via reflection. Here the variable bean in line 569 points to HelloWorld instance, and value points to user instance.

Once field.set(bean, value) is done, we can observe in debugger that the user attribute in HelloWorld instance is already injected successfully.

要获取更多Jerry的原创文章,请关注公众号"汪子熙":
技术图片



以上是关于Spring框架里注解@Autowired的工作原理的主要内容,如果未能解决你的问题,请参考以下文章

Spring框架bean的配置:基于注解的配置,Autowired 自动装配 Bean,泛型依赖注入

构造函数上的 Spring @Autowired 注释如何工作?

Spring注解@Autowired是如何工作的?

整理:spring注解 @Autowired @Qualifier @Resource

@Autowired注解与@resource注解的区别(十分详细)

Spring的注解@Qualifier注解