Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the Spring Bean Lifecycle

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to understand the Spring Bean life cycle, in view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

There are already blogs with multiple Bean lifecycles online, but many are based on older versions and have recently turned the whole process into a flowchart. The flow of the entire declaration cycle is illustrated later in the form of flowcharts, instructions, and code. Note that because there is a lot of code, the flow chart here only draws a general flow, which can go deep into the code.

First, obtain Bean

The first stage is to obtain Bean.

The entry to the flowchart here is the doGetBean method of the AbstractBeanFactory class, which can be read in conjunction with the previous getBean method analysis article. The main process is

1. Deal with the name of Bean first, because if the Bean name that begins with "&" indicates that you are getting the corresponding FactoryBean object

2. Get the singleton Bean from the cache, and further determine whether the Bean is being created. If so, wait for the creation to be completed, otherwise the Bean object will be returned directly.

3. If there is no singleton Bean cache, resolve the circular dependency first.

4. After parsing, get the parent class BeanFactory, and then call the getBean method of the parent class. If it does not exist, merge first and then create a Bean.

2. Before creating Bean2.1, creating Bean

Logic before you actually create a Bean

The corresponding code for this flowchart is in the createBean method of the AbstractAutowireCapableBeanFactory class.

1. First, you will get the Class object in the RootBeanDefinition object and make sure that the Class of the Bean to be created has been associated.

2. Three conditions will be checked here

(1) whether the beforeInstantiationResolved field in the attribute of Bean is true. The default is false.

(2) Bean is native Bean.

(3) the hasInstantiationAwareBeanPostProcessors attribute of Bean is true, which is set when Spring is ready to refresh the container money BeanPostProcessors. If the current Bean implements InstantiationAwareBeanPostProcessor, this attribute will be true.

When all three conditions exist, the postProcessBeforeInstantiation method of the implemented InstantiationAwareBeanPostProcessor API is called, and then the returned Bean is obtained. If the returned Bean is not null, the postProcessAfterInitialization method of the implemented BeanPostProcessor interface is also called. This is explained in the code:

3. If one of the above three conditions is not met, the implemented method will not be called. These BeanPostProcessors implementation methods are not called here by default. Then proceed to the following doCreateBean method.

2.1 actually create a Bean,doCreateBean

DoCreateBean method logic

The implementation of this code is still in the AbstractAutowireCapableBeanFactory method. The process is

1. First check whether the instanceWrapper variable is null. Here it is usually null, unless the Bean you are creating currently exists in factoryBeanInstanceCache, which is a collection of FactoryBean that has not been created yet.

2. Call the createBeanInstance method to instantiate Bean, which will be explained later

3. If the current RootBeanDefinition object has not called the method of the implemented MergedBeanDefinitionPostProcessor interface, it will be called.

4. When the following three points are met (1) is a singleton Bean (2) attempts to resolve circular references between bean (3) bean is currently being created, it will further check whether the SmartInstantiationAwareBeanPostProcessor interface is implemented, and if so, call the getEarlyBeanReference method that is implemented.

5. Call the populateBean method to populate the attributes, which will be explained later.

6. Call the initializeBean method to initialize Bean, which will be explained later

2.1.1 instantiating Bean,createBeanInstance

Instantiate Bean

The logic here is a little more complicated, and the flow chart has been simplified. Briefly describe the process according to the code:

1. First check whether Class is associated, and whether the corresponding modifier is public.

2. If the user defines a function instantiated by Bean, it calls and returns

3. If the current Bean implements the FactoryBean interface, call the getObject method of the corresponding FactoryBean interface.

4. Process according to whether the construction parameters are passed in getBean.

4.1 if no construction parameters are passed, check whether there is a cached no-parameter constructor, and create it directly using the constructor. If not, the instantiateBean method will be called to get the instantiated policy CglibSubclassingInstantiationStrategy by default, and then instantiate Bean. Finally return

4.2 if the construction parameter is passed in, it will first check whether the SmartInstantiationAwareBeanPostProcessor interface is implemented, and if so, it will call determineCandidateConstructors to get the returned candidate constructor.

4.3 check whether one of the four conditions is met

(1) the constructor is not null

(2) the injection mode of the association obtained from RootBeanDefinition is constructor injection (setter injection without construction parameters, or constructor injection)

(3) contains structural parameters.

(4) the construction parameter passed in by getBean method is not empty.

If one of them is satisfied, the returned candidate constructor will be called to instantiate Bean and return. If both are not satisfied, the appropriate parameterized constructor will be selected according to the construction parameters and Bean will be instantiated and returned.

5. If none of the above has a suitable constructor, use the no-parameter constructor directly to create and return Bean.

2.1.2 populating Bean,populateBean

Populate Bean

Let's talk about the process according to the code here.

1. Check whether the current Bean implements the postProcessAfterInstantiation method of InstantiationAwareBeanPostProcessor, and end the filling of Bean. 2. Separate the injected Bean by type from the injected Bean by name. If the injected Bean has not been instantiated, it will be instantiated here, and then put into the PropertyValues object. 3. If you implement the postProcessProperties of the InstantiationAwareBeanPostProcessor class, call this method and get the return value. If the return value is null, you may have implemented the expired postProcessPropertyValues method. Here, you need to call the postProcessPropertyValues method 4 to fill in the parameters.

2.1.3 initialize Bean,initializeBean

Initialize Bean

At the same time, it is explained here according to the code and the flow chart.

1. If Bean implements BeanNameAware, BeanClassLoaderAware, and BeanFactoryAware, the corresponding implementation method is called.

2. Bean is not null and bean is not synthetic. If the postProcessBeforeInitialization of BeanPostProcessor is implemented, the implemented postProcessBeforeInitialization method will be called. The postProcessBeforeInitialization method is implemented in the ApplicationContextAwareProcessor class. This class will be added when the Spring refresh container prepares beanFactory, and it will be called here, and the call will check whether Bean is the implementation class of EnvironmentAware, EmbeddedValueResolverAware, ResourceLoaderAware, ApplicationEventPublisherAware, MessageSourceAware, and ApplicationContextAware. The corresponding implementation method is called here. The code is as follows

1. Instantiate Bean and then check whether the afterPropertiesSet method of InitializingBean is implemented, and if so, it will be called

2. Bean is not null and bean is not synthetic. If the postProcessBeforeInitialization of BeanPostProcessor is implemented, the implemented postProcessAfterInitialization method will be called.

At this point, the process of creating the Bean is gone, and the rest is when the container is destroyed.

Third, destory method and destroy Bean

After Bean is created, it will check whether the user has specified destroyMethodName and implemented the requiresDestruction method of the DestructionAwareBeanPostProcessor interface. If so, it will record it and save it in the DisposableBeanAdapter object and in the disposableBeans property of bean. The code is in the registerDisposableBeanIfNecessary of AbstractBeanFactory

The destroyBean method of AbstractAutowireCapableBeanFactory is finally called when the Bean is destroyed.

Here is to create a DisposableBeanAdapter object that implements the Runnable interface and calls the destroy method of the implemented DisposableBean interface in the implemented run method. And when creating a DisposableBeanAdapter object, the invokeDisposableBean variable is set according to whether the incoming bean implements the DisposableBean interface. Does this variable table actually implement the DisposableBean interface?

IV. Summary

Finally, there is a big process.

Preparation phase before instantiation

Before instantiation

After instantiation

Before initialization

This is the answer to the question on how to understand the life cycle of Spring Bean. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report