网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

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

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

创新互联是一家业务范围包括IDC托管业务,虚拟空间、主机租用、主机托管,四川、重庆、广东电信服务器租用,成都二枢服务器租用托管,成都网通服务器托管,成都服务器租用,业务范围遍及中国大陆、港澳台以及欧美等多个国家及地区的互联网数据服务公司。

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的工作原理

当前文章:Spring框架里注解@Autowired的工作原理
转载注明:http://bjjierui.cn/article/ishepo.html

其他资讯