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

/wp-content/uploads/2016/08/clipboard1_1013534.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.

/wp-content/uploads/2016/08/clipboard2_1013535.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.

/wp-content/uploads/2016/08/clipboard3_1013536.png


When the HelloWorld bean is initialized:

/wp-content/uploads/2016/08/clipboard4_1013538.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.

/wp-content/uploads/2016/08/clipboard5_1013539.png

/wp-content/uploads/2016/08/clipboard6_1013543.png

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

/wp-content/uploads/2016/08/clipboard7_1013544.png

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

/wp-content/uploads/2016/08/clipboard8_1013545.png

/wp-content/uploads/2016/08/clipboard9_1013546.png

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

/wp-content/uploads/2016/08/clipboard10_1013548.png

/wp-content/uploads/2016/08/clipboard11_1013549.png

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

/wp-content/uploads/2016/08/clipboard12_1013550.png

/wp-content/uploads/2016/08/clipboard13_1013551.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.

/wp-content/uploads/2016/08/clipboard14_1013552.png

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

/wp-content/uploads/2016/08/clipboard15_1013553.png



To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply