Chapter 7 - Bean life cycle and extension points of Spring

Keywords: Java Spring


The core of Spring is the IoC container. It is very important to understand the life cycle of beans, which is very helpful for the application and extension of Spring in the project.

1, Life cycle

The life cycle of a Bean mainly consists of four stages: instantiation, attribute filling, initialization and destruction, plus class loading and use. The whole process is as follows:

2, Bean extension

Spring provides extension points at each stage, which can be divided into two types:

  • Special extension point: it is used for the extension of a single Bean. When defining the Bean class, implement the interface to extend the function.
  • Common extension point: it is used for the extension of all beans, and the class implementation interface is defined separately to extend the function.

1. Dedicated extension point

Aware interface

Aware interface can inject Bean information or context information during attribute filling.

For example, you can inject the name of the current Bean into the class by implementing the BeanNameAware interface.

public class OneBeanExample implements BeanNameAware {

    private String beanName;

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }
}

Spring provides many Aware sub interfaces that can be used, including:

Aware interfaceInjection dependency
BeanNameAwareThe name of the Bean
BeanFactoryAwareBeanFactory of the current context
ApplicationContextAwareApplicationContext of the current context
ApplicationEventPublisherAwareEvent publisher for the current context ApplicationEventPublisher
BeanClassLoaderAwareClass loader to load Bean classes

InitializingBean and DisposableBean interfaces

If you want to add custom logic during Bean initialization, you can implement the InitializingBean interface.

If you want to add custom logic when the Bean is destroyed, you can implement the DisposableBean interface.

public class OneBeanExample implements InitializingBean, DisposableBean {

    @Override
    public void afterPropertiesSet() {
		// do some initialization work
    }

    @Override
    public void destroy() {
		// do some destruction work
    }
}

In addition to the above two callback interfaces, you can also specify custom initialization and destruction methods when registering beans.

@The initMethod attribute of the Bean annotation specifies the Bean initialization method, and the destroyMethod attribute specifies the Bean destruction method.

public class OneBeanExample {

    public void init() {
        // do some initialization work
    }

    public void destroy() {
        // do some destruction work
    }
}

@Configuration
public class AppConfig {

    @Bean(initMethod = "init", destroyMethod = "destroy")
    public OneBeanExample oneBeanExample() {
        return new OneBeanExample();
    }
}

The init method and destroy method attributes corresponding to the < bean > tag of the XML configuration.

You can also use the JDK's @ PostConstruct and @ PreDestroy annotations to specify initialization and destruction methods.

public class OneBeanExample {

    @PostConstruct
    public void init() {
        // do some initialization work
    }

    @PreDestroy
    public void destroy() {
        // do some destruction work
    }
}

The above three methods can define the methods to be executed during Bean initialization and destruction.

InitializingBean and DisposableBean interfaces are strongly coupled with Spring.
When the project does not rely on Spring, the second or third method is recommended.

2. General extension point

The general extension point is valid for all beans and needs to be implemented by defining separate classes. There are three main interfaces:

  • BeanPostProcessor interface
  • InstantiationAwareBeanPostProcessor interface
  • DestructionAwareBeanPostProcessor interface

BeanPostProcessor interface

Implementing this interface can add custom logic before and after Bean initialization.

@Component
public class BeanInitProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // before initialization work
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // after initialization work
        return bean;
    }
}

InstantiationAwareBeanPostProcessor interface

Implementing this interface can add custom logic before and after Bean instantiation.

@Component
public class BeanInstanceProcessor implements InstantiationAwareBeanPostProcessor {

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        // before instantiation work
        return null;
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        // after instantiation work
        return true;
    }
}

DestructionAwareBeanPostProcessor interface

Implementing this interface can add custom logic before Bean destruction.

@Component
public class BeanDestroyProcessor implements DestructionAwareBeanPostProcessor {

    @Override
    public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
        // before destruction work
    }
}

3. Life cycle extension point example

The four stages of the Bean life cycle support extension, and custom logic can be added to each stage.

3.1 instantiation

The Spring container instantiates the Bean object in this step.

Implement two extension methods of the instantiaawarebeanpostprocessor interface, and add extensions before and after instantiation.

3.2 attribute filling

In this step, the Spring container fills in properties, such as injecting dependencies through the Setter method.

After the attribute is filled, the Bean information or context information is injected through the Aware interface extension.

3.2 initialization

The Spring container initializes the Bean at this step.

Implement the two extension methods of the BeanPostProcessor interface, and add extensions before and after initialization.

In the initialization phase, we mentioned three ways to specify the initialization method. Generally, one is OK.

If three methods are used at the same time, the methods specified in the three methods are the same, and the method is executed only once. When the methods specified in the three methods are different, they are executed in the order in the figure.

3.4 destruction

The Spring container destroys the Bean in this step to release external resources.

Implement the extension method of DestructionAwareBeanPostProcessor interface. You can add extensions before destruction.

In the destruction stage, we mentioned three ways to specify the destruction method. Generally, one is OK.

If three methods are used at the same time, the methods specified in the three methods are the same, and the method is executed only once. When the methods specified in the three methods are different, they are executed in the order in the figure.

4. Life cycle extension point sequence

In the life cycle of Bean, the execution sequence of general extension points, special extension points and their corresponding methods is as follows:

3, Appendix

1. Configuration properties

attributedescribe
Init method attribute of < bean >Specify a custom initialization method in the XML based configuration container
Destroy method attribute of < bean >Specify a custom destruction method in the XML based configuration container

2. Common notes

annotationdescribe
@initMethod property of BeanIn the Java based configuration container, specify the custom initialization method
@destroyMethod property of BeanIn the Java based configuration container, specify a custom destruction method
@PostConstructUse the JDK annotation to specify the method of initialization execution
@PreDestroyUse the JDK annotation to specify the method of destruction execution

3. Example code

Gitee warehouse: https://gitee.com/code_artist/spring
Project module: Spring IOC
Example path: cn.codertist.spring.bean.life

The latest article focuses on the CodeArtist code maker's official account.

Posted by dourvas on Sun, 05 Dec 2021 02:24:37 -0800