“This is the sixth day of my participation in the First Challenge 2022. For details: First Challenge 2022”
This article focuses on the Bean loading process and how Spring solves the problem of loop dependencies. As usual, the diagram first, combined with the diagram and source code together to better understand, first look at the Bean load is the sequence diagram:
Next, take a look at the entry code that initializes all non-lazy-loaded beans during the SpringBoot startup process and, combined with the sequence diagram above, enter the main code interpretation.
Sort out the general process:
- Loading beans from singletons. Why are spring beans singletons
- Instantiate the bean
- Dependency check, in this step, the dependency can not be found or the dependency project because of the version of the interface error
- Transform BeanDefinition to RootBeanDefinition
- Create beans for different scopes
- Type conversion
Then continue the analysis with the sequence diagram above
@1.1 getSingleton(beanName) gets the singleton bean from the cache
Spring retrieves the Bean from singletonObjects, then retrieves the Bean from earlySingletonObjects, then retrieves the Bean from singletonFactories, and calls getOb The ject() method creates the bean. Explain the function of the maps above.This means that Spring beans are stored in different caches at different stages.
@ 1.2 getMergedLocalBeanDefinition (beanName)
So this method will change the BeanDefinition to RootBeanDefinition, and if it’s a subclass you can merge the BeanDefinition of the parent class, so basically what does RootBeanDefinition do, it defines the Bean, what is the Bean Type, need to inject the attributes, define the Bean constructor, etc., due to space problems only describe the Bean loading process, not in the overview.
@ 1.3 getSingleton (beanName ObjectFactory), This method takes a beanName and an inner class. The inner class method returns createBean(beanName, MBD, args), which literally means createBean.
The process is as follows:
- Determines whether the Bean has been loaded
- No load, record beanName status
- Call createBean to createBean (important)
- Call the method after the Bean is created
- Add cache and remove various secondary states
The next section continues with the creation and instantiation of beans and loading methods, as well as the handling of loop dependencies.