温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-08-11 20:48:17 来源:ITPUB博客 阅读:119 作者:i042416 栏目:编程语言

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

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

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.

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

How is this behavior implemented by Spring framework?

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

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

When the HelloWorld bean is initialized:

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

Since it has the following source code:

@Autowiredprivate 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.

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

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

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

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

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

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的工作原理
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI