Spring框架里注解@Autowired的工作原理
发布日期:2021-06-30 14:20:09 浏览次数:2 分类:技术文章

本文共 1556 字,大约阅读时间需要 5 分钟。

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:

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

(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的原创文章,请关注公众号"汪子熙":

转载地址:https://jerry.blog.csdn.net/article/details/105917008 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:SAP ABAP和Java里的弱引用(WeakReference)和软引用(SoftReference)
下一篇:使用ABAP代码创建SAP Netweaver透明表(transparent table)

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月08日 02时15分08秒