Spring Bean's life cycle quick memory

  1. Introduction
    "Can you describe the life cycle of Spring Bean?" This is a common question for interviewers to investigate Spring. It can be seen that it is a very important knowledge point in Spring.

When I was preparing for the interview, I searched for the answers on the Internet, and most of them used the process given in the figure below as the answer.
insert image description here

How to remember the life cycle of Spring Bean

But when I saw the picture for the first time, I had a lot of troubles, "Aware, BeanPostProcessor... what are these! And there are so many steps, too many, how should I remember!".

In fact, to remember the process, we still need to understand it first. This article will help understand the Bean life cycle from the following two aspects:

Summary process of life cycle: Summarize the life cycle of Bean and understand it in combination with code;
Function of extension point: Introduce in detail the function of extension point involved in the life cycle of Bean.
2. Summary process of life cycle
The life cycle of Bean can be summed up in 4 stages:

Instantiation;
attribute assignment (Populate);
initialization (Initialization);
destruction (Destruction).
How to remember the life cycle of Spring Bean
insert image description here

Instantiation: step 1, instantiate a bean object;
attribute assignment: step 2, set related attributes and dependencies for the bean;
initialization: steps 3~7, there are many steps, of which steps 5 and 6 are initialization operations, steps 3 and 4 are executed before initialization, step 7 is executed after initialization, and can be used by users after this stage ends; Destroyed related call interface, in order to execute the corresponding method when the bean is actually destroyed in the 9th and 10th steps later
.
Let's take a visual look at the code together. In the doCreateBean() method, we can see that these four stages are executed in sequence:

From the source code of Spring, we can see its execution process intuitively, and we can remember its process from these four stages, instantiation, attribute assignment, initialization, and destruction. The more detailed one is initialization, which involves the concepts of Aware, BeanPostProcessor, InitializingBean, and init-method. These are extension points provided by Spring, and their specific functions will be described in the next section.

  1. The role of the extension point
    3.1 Aware interface
    If Spring detects that the bean implements the Aware interface, it will inject corresponding dependencies into it. So by making the bean implement the Aware interface, the corresponding Spring container resources can be obtained in the bean.

The Aware interfaces provided in Spring are:

BeanNameAware: Inject the corresponding beanName of the current bean;
BeanClassLoaderAware: Inject the ClassLoader that loads the current bean;
BeanFactoryAware: Inject the reference of the current BeanFactory container.
Its code is implemented as follows:

// AbstractAutowireCapableBeanFactory.javaprivate void invokeAwareMethods(final String beanName, final Object bean) {    if (bean instanceof Aware) {        if (bean instanceof BeanNameAware) {            ((BeanNameAware) bean).setBeanName(beanName);        }        if (bean instanceof BeanClassLoaderAware) {            ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);        }        if (bean instanceof BeanFactoryAware) {            ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);        }    }}

The above is for BeanFactory type containers, and for ApplicationContext type containers, Aware interfaces are also provided, but the injection implementation of these Aware interfaces is injected through BeanPostProcessor, but its role is still to inject dependencies.

EnvironmentAware: inject Environment, generally used to obtain configuration properties;
EmbeddedValueResolverAware: inject EmbeddedValueResolver (Spring EL parser), generally used for parameter parsing;
ApplicationContextAware (ResourceLoader, ApplicationEventPublisherAware, MessageSourceAware): inject ApplicationContext container itself.
Its code is implemented as follows:

// ApplicationContextAwareProcessor.javaprivate void invokeAwareInterfaces(Object bean) {    if (bean instanceof EnvironmentAware) {        ((EnvironmentAware)bean).setEnvironment(this.applicationContext.getEnvironment());    }    if (bean instanceof EmbeddedValueResolverAware) {        ((EmbeddedValueResolverAware)bean).setEmbeddedValueResolver(this.embeddedValueResolver);    }    if (bean instanceof ResourceLoaderAware) {        ((ResourceLoaderAware)bean).setResourceLoader(this.applicationContext);    }    if (bean instanceof ApplicationEventPublisherAware) {        ((ApplicationEventPublisherAware)bean).setApplicationEventPublisher(this.applicationContext);    }    if (bean instanceof MessageSourceAware) {        ((MessageSourceAware)bean).setMessageSource(this.applicationContext);    }    if (bean instanceof ApplicationContextAware) {        ((ApplicationContextAware)bean).setApplicationContext(this.applicationContext);    }}

3.2 BeanPostProcessor
BeanPostProcessor is a powerful extension point provided by Spring for * modifying beans *, which can act on all beans in the container, and its definition is as follows:

public interface BeanPostProcessor { // pre-initialization processing default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } // post-initialization processing default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; }}Common scenarios are
:

For the implementation class of the marker interface, perform custom processing. For example, the ApplicationContextAwareProcessor mentioned in Section 3.1 injects corresponding dependencies into it; as another example, the custom class that implements the decryption interface will decrypt its properties;
provide proxy implementation for the current object. For example, the Spring AOP function generates the proxy class of the object and returns it.

// AbstractAutoProxyCreator.javapublic Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {    TargetSource targetSource = getCustomTargetSource(beanClass, beanName);    if (targetSource != null) {        if (StringUtils.hasLength(beanName)) {            this.targetSourcedBeans.add(beanName);        }        Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);        Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);        this.proxyTypes.put(cacheKey, proxy.getClass());        // 返回代理类        return proxy;    }    return null;}

3.3 InitializingBean and init-method
InitializingBean and init-method are extension points provided by Spring for bean initialization.

The InitializingBean interface is defined as follows:

public interface InitializingBean { void afterPropertiesSet() throws Exception;}
Write the initialization logic in the afterPropertiesSet() method.

Specify the init-method method to specify the initialization method:

<?xml version="1.0" encoding="UTF-8"?>

DisposableBean and destroy-method are similar to the above and will not be described here.

  1. Summary
    Finally, summarize how to remember the life cycle of Spring Bean:

The first is the four major stages of instantiation, property assignment, initialization, and destruction;
and then the specific operations of initialization, including dependency injection of the Aware interface, processing of BeanPostProcessor before and after initialization, and initialization operations of InitializingBean and init-method; specific operations of destruction include registration of
related destruction callback interfaces, and finally destroy through DisposableBean and destroy-method.

Guess you like

Origin blog.csdn.net/Wis57/article/details/131548414