Moment For Technology

The Spring framework annotates how @autowired works

Posted on May 28, 2023, 12:44 a.m. by Nitara Kalla
Category: The back-end Tag: The back-end

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?

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:

private User user;
Copy the code

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:

Inserted to The map matchingBeans 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.

For more of Jerry's original articles, please follow the public account "Wang Zixi ":

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.