Multiple ways of Bean initialization and destruction in Spring


Spring supports declaring the initialization method when the Bean is loaded. This method will be executed before the Bean object is initialized. You can specify some specific behaviors for the object. When the same Bean is destroyed, this action is also supported. Among them, because the scope of the object is different, the form of destruction is slightly different. There is no difference in initialization, whether it is a singleton, prototype, request, session, global session, etc. when they are created, there is no difference in initialization, but the destruction will be slightly different. The singleton mode will not be destroyed by default, only when the Spring container is destroyed Only when the Bean is destroyed will it execute its destruction method. Session, request, etc. will be destroyed when the scope reaches, and will not exist for a long time, so their destruction method is called after the scope is executed.

1. Multiple initialization methods of Bean

Spring supports a total of three ways to initialize beans, followed by using the PostConstruct annotation on the method, implementing the InitializtingBean interface to rewrite the corresponding method, and declaring the init-method method to achieve, and the three of them support parallelism. That is to say, we can use all three. When all three are used, they are executed in the following order, that is, the restrictive PostConstruct annotation method, then the InitializingBean method, and finally the init-method method.

1. PostConstruct Notes

As shown below, the configuration class is used for injection here, because after a while the init-method must be implemented using the configuration class. When the container is started and the TestA bean is loaded, its initialization method will be executed.

@Configuration
public class TestInitmestond {
    
    

    @Bean
    public TestA getBeanA(){
    
    
        return new TestA();
    }
}

class TestA{
    
    
    @PostConstruct
    public void postConstructor(){
    
    
        System.out.println("这是使用了PostConstruct注解的初始化方法");
    }

}

2. Implement the InitializingBean interface

The following is a combination of the first and second initialization methods:

@Configuration
public class TestInitmestond {
    
    

    @Bean
    public TestA getBeanA(){
    
    
        return new TestA();
    }
}

class TestA implements InitializingBean {
    
    

    @Override
    public void afterPropertiesSet() throws Exception {
    
    
        System.out.println("这是实现InitializingBean的初始化方法");
    }

    @PostConstruct
    public void postConstructor(){
    
    
        System.out.println("这是使用了PostConstruct注解的初始化方法");
    }

}

3. Declare the init-method method

The init-method method must use the configuration class to load the Bean before it can be configured, because this attribute is the attribute of the Bean tag, which is also the attribute of the Bean annotation in the annotation, so we cannot specify it when we use other IOC annotations such as Component.

@Configuration
public class TestInitmestond {
    
    

    @Bean(initMethod = "initMethod")
    public TestA getBeanA(){
    
    
        return new TestA();
    }
}

class TestA implements InitializingBean {
    
    

    @Override
    public void afterPropertiesSet() throws Exception {
    
    
        System.out.println("这是实现InitializingBean的初始化方法");
    }

    @PostConstruct
    public void postConstructor(){
    
    
        System.out.println("这是使用了PostConstruct注解的初始化方法");
    }

    public void initMethod(){
    
    
        System.out.println("这是使用了init-method声明的初始化方法");
    }
}

Next, start the container to show their execution order, as follows:
insert image description here
You can see that their order is fixed: PostConstruct—>initializingBean—>init-method.

Two, Bean's multiple destruction methods

The same Spring also supports three destruction methods, and these three destruction methods are completely corresponding to the three creation methods. At the same time, like the initialization method, Spring also supports the parallelization of three destruction methods. And their parallel order is fixed: execute PreDestroy–>DisposableBean–>destroy-method.

1. PreDestroy annotation

Here the container is created by manually starting, and then a destruction hook is set for the container, so that when the container is destroyed, we can execute the destruction method. The destruction method of the singleton mode can only pass this test. If we Stopping the service of IDEA directly will not execute the destruction method. However, for beans whose scope is not singleton, for example, request can reflect the destruction action in normal services.

public class TestDestroyMethod {
    
    
    //手动启动容器,模拟关闭
    public static void main(String[] args) {
    
    
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(TestConfig.class);
        annotationConfigApplicationContext.start();
        annotationConfigApplicationContext.registerShutdownHook();
    }
}
@Configuration
class TestConfig{
    
    

    @Bean
    public TestB getBean(){
    
    
        return new TestB();
    }
}
class TestB{
    
    

    @PreDestroy
    public void preDestroy(){
    
    
        System.out.println("这是使用PreDestroy注解的销毁方法");
    }
}

2. Implement the DisposableBean interface

This is to directly implement the interface rewriting destroy method

public class TestDestroyMethod {
    
    
    //手动启动容器,模拟关闭
    public static void main(String[] args) {
    
    
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(TestConfig.class);
        annotationConfigApplicationContext.start();
        annotationConfigApplicationContext.registerShutdownHook();
    }
}
@Configuration
class TestConfig{
    
    

    @Bean
    public TestB getBean(){
    
    
        return new TestB();
    }
}
class TestB implements DisposableBean {
    
    

    @PreDestroy
    public void preDestroy(){
    
    
        System.out.println("这是使用PreDestroy注解的销毁方法");
    }

    @Override
    public void destroy() throws Exception {
    
    
        System.out.println("这是实现DisposableBean的方法");
    }
}

3. Declare the destroy-method method

Below is the code that combines the three destruction methods

public class TestDestroyMethod {
    
    
    //手动启动容器,模拟关闭
    public static void main(String[] args) {
    
    
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(TestConfig.class);
        annotationConfigApplicationContext.start();
        annotationConfigApplicationContext.registerShutdownHook();
    }
}
@Configuration
class TestConfig{
    
    

    @Bean(destroyMethod = "destroyMethod")
    public TestB getBean(){
    
    
        return new TestB();
    }
}
class TestB implements DisposableBean {
    
    

    @PreDestroy
    public void preDestroy(){
    
    
        System.out.println("这是使用PreDestroy注解的销毁方法");
    }

    @Override
    public void destroy() throws Exception {
    
    
        System.out.println("这是实现DisposableBean的方法");
    }

    public void destroyMethod(){
    
    
        System.out.println("这是制定了destroy-method的销毁方法");
    }
}

The following is a screenshot of the execution. You can see that the three destruction methods have the same order as the initialization method. In fact, the initialization method and the destruction method have a corresponding relationship.
PostConstruct and PreDestroy are a group, InitializingBean and DisposableBean are a group, init-method and destroy-method are a group.
insert image description here

3. Summary

This article summarizes the various ways of initialization and destruction of beans in Spring. There is nothing special about it. I hope it can help you passing by.
insert image description here

Guess you like

Origin blog.csdn.net/m0_46897923/article/details/130191626