Bean loading

The loading process of beans is a complicated process. The source code of doGetBean() is very long. Here, we only list the key loading steps, which is convenient for future review. Those who are learning for the first time can also follow this step and read the source code carefully.

Bean loading process

1. Convert the corresponding beanName

The incoming name may be the name of the bean, or it may be a FactoryBean

Note: The Bean object obtained through getBean(String BeanName) is not the implementation class object of FactoryBean, but the object returned by the getObject() method in this implementation class. To get the implementation class of FactoryBean, it is necessary to getBean(&BeanName) and add & before BeanName.

 

2. Attempt to load the singleton from the cache

For a bean whose scope is singleton, it will only be created once in a container, so loading a singleton class is first obtained in the cache. If the cache is not loaded in the singletonFactories, if there is dependency injection in the bean, it may appear Circular dependencies.

Avoid circular dependency method: Before the bean is loaded, the ObjectFactory that created the bean is exposed to the cache in advance. Once the next bean is created, it depends on the previous bean, and the ObjectFactory can be used directly.

 

3. bean instantiation

The bean obtained from the cache is the most primitive state, and what we often need is the bean returned by the bean-factory method defined in the factory bean, and getObjectForBeanInstance does this work

 

4. Prototype pattern dependency checking

When A has not been created, since the creation of B returns to create A again, it will cause a circular dependency, so when the result of the prototype dependency check is true, an exception is thrown

 

5. Detect parentBeanFactory

The currently loaded xml configuration file does not contain beanName, it can only be loaded in parentBeanFactory, but if parentBeanFactory is null, no matter whether xml contains beanName, it will not be loaded in parentBeanFactory

 

6. Convert the GernericBeanDefinition that stores the XML configuration file to a RootBeanDefinition

The Bean information read in XML is stored in the GernericBeanDefinition, but the subsequent Bean processing is all in the RootBeanDefinition, so a conversion needs to be done here

 

7. Find dependencies

When a class is initialized, the dependencies of the bean will be initialized first.

 

8. Create beans for different scopes

Beans need to be created for different scopes

 

9. Type conversion

If the incoming parameter requiredType is the same as the bean type, no type conversion is required. If it is different, the bean needs to be converted.

 

Well, the above are the main points. If you want to learn in detail, it is recommended to read the source code, read the source code, read the source code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325177772&siteId=291194637