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.
【java|Java注解@Autowired的工作原理】
文章图片
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.
文章图片
(3) 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的原创文章,请关注公众号"汪子熙":
文章图片
推荐阅读
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- Spring注解驱动第十讲--@Autowired使用
- =======j2ee|spring用注解实现注入的@resource,@autowired,@inject区别
- SqlServer|sql server的UPDLOCK、HOLDLOCK试验
- jvm|【JVM】JVM08(java内存模型解析[JMM])