Suppose I have anamed 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 metadataure below, the getClass 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 (in DefaultLis leBeanFactory ):
Once found, the found result is added to array candateNames:
Then the constructor of User bean class is called ( stilled by getBean call ), the user instance is created by calling constructor:
The created user instance together with its name “user” is inserted to thematchingBeans.
- 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 points to user instance.
Once field.set(bean, value) is done, we can observe in deger that the user attribute in HelloWorld instance is already injected successfully.
本站部分文章源于互联网，本着传播知识、有益学习和研究的目的进行的转载，为网友免费提供。如有著作权人或出版方提出异议，本站将立即删除。如果您对文章转载有任何疑问请告之我们，以便我们及时纠正。PS：推荐一个微信公众号: askHarries 或者qq群：474807195，里面会分享一些资深架构师录制的视频录像：有Spring，MyBatis，Netty源码分析，高并发、高性能、分布式、微服务架构的原理，JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源，目前受益良多