autowired java_Java注解@Autowired的工作原理

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

89f84bf03a5b50f0cad28e30e0f83bbe.png

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.

8e9af29849f0d3fd108304f6ba128c01.png

How is this behavior implemented by Spring framework?

(1) in Spring container implementation’s refresh method, all singleton beans will be initialized by default.

c627175f6d93d3640e7fad38702b6fd0.png

When the HelloWorld bean is initialized:

4daf214dc1f115931df44966d72141cf.png

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.

df14c1cafdec53d27cdfc625b35d6ac5.png

60fb36a3aa09d23d377e9ac509a5a25b.png

(2) In doResolveDependency, the definition for User bean is searched based on this.beanDefinitionNames ( list in DefaultListableBeanFactory ):

23917af68781b1f1399991ea0f60c68c.png

Once found, the found result is added to array candidateNames:

c742a73f21e7f606348e04c83d67ad6b.png

dfef41abacce22addbf36664a7dc0a75.png

Then the constructor of User bean class is called ( still triggered by getBean call ), the user instance is created by calling constructor:

eb2f05f3ea7235bb1b3bbf8df119596c.png

d19b169a5d521a3183a7c8f23b168080.png

The created user instance together with its name “user” is inserted to the map matchingBeans.

055b1c3ad5a0e294f6d6071f6e70ba12.png

6332c9b5b8faa2face0ea4caf6e22849.png

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

7b62c7303cd3dc14a81d2738a9c01362.png

Once field.set(bean, value) is done, we can observe in debugger that the user attribute in HelloWorld instance is already injected successfully.

9e182d0df6d02ed2308c5bb5b64a3b63.png

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

b0dc89a8778f8f42f17da2081659998f.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值