[Spring source code analysis] the life cycle of the bean

flow chart:

 

There are 13 stages

1. Bean meta information configuration stage

Bean information is defined in 4 ways

  1. API way
  2. Xml file method
  3. Properties file method
  4. Annotation method

API method:

It implements the BeanDefinition interface. There are 5 specific implementation classes:

  • RootBeanDefinition: Root bean definition information. Indicates a bean without a parent bean
  • ChildBeanDefinition: Child bean definition information. Need to specify the parent bean through the parentName property
  • GenericBeanDefinition: Generic bean definition information. It can represent a bean without a parent bean, or a child bean with a parent bean. There is also a parent attribute.
  • ConfigurationClassBeanDefinition: the bean information defined by the @bean method in the configuration class.
  • AnnotatedGenercBeanDefinition: bean information defined by annotation

Just instantiate it directly.

Xml way:

<bean id="bean名称">
    <constructor-arg index="0" value="bean的值" ref="引用的bean名称" />
</bean>

Finally, it will be parsed into the configuration method of the API through the XmlBeanDefinitionReader class

Properties file method:

employee.(class)=MyClass       // 等同于:<bean class="MyClass" />
employee.(abstract)=true       // 等同于:<bean abstract="true" />
employee.group=Insurance       // 为属性设置值,等同于:<property name="group" value="Insurance" />
employee.usesDialUp=false      // 为employee这个bean中的usesDialUp属性设置值,等同于:等同于:<property name="usesDialUp" value="false" />

Finally, it will be parsed into the configuration method of the API through the PropertiesBeanDefinitionReader class

Annotation method:

@bean or @Compontent will eventually be resolved into the configuration method of the API

2. Bean meta-information analysis stage

There are three main ways of meta-information analysis:

  1. xml file definition bean analysis (XmlBeanDefinitionReader)
  2. The analysis of properties file definition bean (PropertiesBeanDefinitionReader)
  3. Annotation method definition bean analysis (PropertiesBeanDefinitionReader)

 

Three, register the Bean to the container

Bean registration interface: BeanDefinitionRegistry (inherited AliasRegistry)

Alias ​​registration interface: AliasRegistry

 

The first three steps occur when the ioc container is created, and the following four to ten steps occur when getBean

Four, BeanDefinition merge phase

The bean definition may have a multi-level parent-child relationship, recursively merged into a RootBeanDefinition containing complete information.

The source code of the merger is as follows:

This RootBeanDefinition will be used in the subsequent stages, and the next step will be to check whether the dependent Bean needs to be loaded, if not, skip it (the picture is not intercepted)

Five, Bean Class loading phase

Convert the bean's class name to an object of type Class.

The source code is as follows:

The specific resolveBeanClass method, go deeper, you can see that the final class object obtained through Class.forName

With the class object, you can start to instantiate through reflection

Six, Bean instantiation stage

(1) Before instantiation

The postProcessBeforeInitialization method of the class that implements the BeanPostProcesstor interface will be executed.

The source code is as follows:

It can be seen that if the bean is returned, spring will directly use the bean, and skip the following bean creation operation (this is an extension point of spring)

(2) Instantiation

This process will use reflection to call the bean constructor to create an instance of the bean, and finally wrap it into a BeanWrapper. (Used decorator mode)

The source code is as follows:

The strategy mode is used here , which is handled in the SimpleInstantiationStrategy class

Finally, the newInstance method (core) of the class called in the InstantiateClass method of the BeanUtils class

Seven, merged BeanDefinition processing

The post-processing class performs some caching processing, which is convenient for later use

It mainly performs callback processing on the class that implements the MergedBeanDefinitionPostProcessor interface. The implementation classes mainly include:

  • AutowiredAnnotationBeanPostProcessor caches the fields or methods annotated with @Autowired and @Value for later use
  • CommonAnnotationBeanPostProcessor caches fields or methods annotated by @Resource, methods annotated by @PostConstruct, and methods annotated by @PerDestroy

Eight, attribute assignment stage

(1) The post-instancing stage

Spring will call the postProcessAfterInstantiation method of the class that implements the InstantiationAwareBeanPostProcessor interface

If it returns false, the next two steps of attribute assignment will be skipped. So it can be used to prevent attribute assignment

(2) The stage before Bean attribute assignment

Mainly through @Autowire and other annotations to generate the value of the attribute for later assignment

It can be seen that when both postProcessProperties and postProcessPropertyValues ​​return empty, it means that the bean does not need to set properties and returns directly to enter the next stage.

PropertyValues ​​saves the settings of all property values ​​in the bean instance object, so we can modify the PropertyValues ​​value in this postProcessProperties

The implementation class of InstantiationAwareBeanPostProcessor is as follows:

The most important thing is the injection operation of these two implementation class values:

  • AutowiredAnnotationBeanPostProcessor of injection and the value of a field or method @Autowired marked @Value
  • CommonAnnotationBeanPostProcessor injects values ​​into fields or methods annotated by @Resource

(3) Bean attribute assignment stage

Circulate PropertyValuesthe attribute value information in the processing , and set the attribute value to the bean instance by invoking the set method through reflection.

After nine bends and eighteen bends, the final call is to assign values ​​to the fields through reflection in the setValue method of BeanWrapperImpl

Nine, Bean initialization phase

(1) Bean Aware interface callback

(2) Operation before Bean initialization

Spring will call the postProcessBeforeInitialization method of the implementation class that implements the BeanPostProcessor interface.

The implementation class includes a lot (not complete)

The key is

  • ApplicationContextAwareProcessor will inject 6 Aware. Including: EnvironmentAware, EmbeddedValueResolverAware, ResourceLoaderAware, ApplicationEventPublisherAware, MessageSourceAware, ApplicationContextAware. Because only the ApplicationContext environment can use these
  • InitDestroyAnnotationBeanPostProcessor is used to call all methods annotated with @PostConstrust

(3) Bean initialization operation

1. Call the afterPropertiesSet method of the Bean that implements the InitializingBean interface

2. Invoke the init-method initialization method specified when defining the bean .

There are three ways to specify the initialization method:

  1. xml method specification    <bean init-method="method name in bean"/>
  2. @bean method specifies  @Bean(initMethod = "initialization method")
  3. The api method specifies  beanDefinition.setInitMethodName(methodName);

(4) Operation after Bean initialization

Spring will call the postProcessAfterInitialization method of the implementation class that implements the BeanPostProcessor interface.

Ten, the stage after bean initialization is complete

In order to ensure that all non-lazy singletons are instantiated, taking into account FactoryBeans

So after all bean initialization is complete, spring will initialize the afterSingletonsInstantiated method that implements the SmartInitializingSingleton interface.

Also includes BeanFactory itself.

The container with ApplicationContext will eventually call preInstantiateSingletons internally to trigger the initialization of all singleton beans.

11. Bean use stage

Needless to say

12. The pre-destruction stage of Bean

There are three ways to destroy the bean:

  1. The destroyBean method of the AbstractAutowireCapableBean class
  2. The destructionSingletons method of the ConfigurableBeanFactory class
  3. ApplicationContext's close method

The Bean destruction phase will be executed in sequence:

  1. Polling the list of beanPostProcessors, if it is of type DestructionAwareBeanPostProcessor, its internal postProcessBeforeDestruction method will be called

  2. If the bean implements the org.springframework.beans.factory.DisposableBean interface, the destroy method in this interface will be called

  3. Call the bean's custom destruction method

 

Spring will call the postProcessBeforeDestruction method of the class that implements the DestructionAwareBeanPostProcessor interface

The implementation class is as follows:

The key is:

  • CommonAnnotationBeanPostProcessor It will call all methods annotated @PreDestroy in the bean

Thirteen, Bean destruction stage

There are 3 ways to customize the destruction method:

  1. Specify the destruction method in xml <bean destroy-method="method name in bean"/>
  2. @Bean specifies the destruction method   @Bean(destroyMethod = "initialization method")
  3. api method specifies the destruction method  beanDefinition.setDestroyMethodName(methodName);

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/sumengnan/article/details/113702527