打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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:

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

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Spring IoC是如何进行依赖注入的
spring为什么推荐使用构造器注入
快速上手spring(1 - 6)
IntelliJ Idea解决Could not autowire. No beans of 'xxxx' type found的错误提示
spring常用注解理解
和喜欢Spring的软件工程师谈谈Spring基于注解的配置
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服