【Spring】06 Life cycle destruction callback


In the Spring framework, Lifecycle Callbacks are a powerful mechanism that allows us to perform specific operations at different stages of the Bean life cycle in the Spring container. This gives us a flexible way to manage and control the bean lifecycle.

1. What is a callback?

In Spring, each Bean has a life cycle, which goes through different stages from creation to destruction. Life cycle callbacks are the mechanism for executing specific methods in these stages.

Spring provides two life cycle callback methods: initialization callback and destruction callback.

Insert image description here

Find out if it is a bit like the template method design pattern!

The previous section introduced the initialization callback. This section will continue to introduce the destruction callback.

2. Destroy callback

The destruction callback is a method that is executed just before the bean is destroyed. Spring provides the following two ways to implement destruction callbacks:

2.1 Implement the DisposableBean interface

1) Configure Bean

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd"
       >

    <bean id="springDemo" class="org.example.cheney.SpringDemo">
        <constructor-arg value="SpringDemo"/>
    </bean>
</beans>

2) Create Spring and implement DisposableBean

package org.example.cheney;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

@Component
public class SpringDemo implements DisposableBean {
    
    
    private String name;

    public SpringDemo(String name) {
    
    
        this.name = name;
    }

    @Override
    public void destroy() throws Exception {
    
    
        System.out.println("Bean " + name + "销毁啦(By DisposableBean)");
    }
}

3) Create startup class

package org.example.cheney;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    
    
    public static void main(String[] args) {
    
    
        String location = "applicationContext.xml";
        AbstractApplicationContext appCxt = new ClassPathXmlApplicationContext(location);
        appCxt.registerShutdownHook();
    }
}

Output result:

Insert image description here

2.2 Configure destroy-method

1) Configure Bean

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd"
       >

    <bean id="springDemo" class="org.example.cheney.SpringDemo" destroy-method="destroyMethod">
        <constructor-arg value="SpringDemo"/>
    </bean>
</beans>

2) Create Spring and create destroyMethod()

package org.example.cheney;

import org.springframework.stereotype.Component;

@Component
public class SpringDemo {
    
    
    private String name;

    public SpringDemo(String name) {
    
    
        this.name = name;
    }


    public void destroyMethod() {
    
    
        System.out.println("Bean " + name + "销毁啦(By destroy-method)");
    }
}

3) Create startup class

package org.example.cheney;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    
    
    public static void main(String[] args) {
    
    
        String location = "applicationContext.xml";
        AbstractApplicationContext appCxt = new ClassPathXmlApplicationContext(location);
        appCxt.registerShutdownHook();
    }
}

Output result:

Insert image description here

3. Execution sequence

The execution sequence of the destruction callback is: implement the destroy method of the DisposableBean interface -> configure destroy-method.

Insert image description here

4. Application scenarios

Life cycle callbacks have a wide range of application scenarios in actual development, such as:

  • Resource release and cleanup: In the destruction callback, you can perform resource release and cleanup logic to ensure that the relevant resources are correctly retrieved when the application is closed or the Bean is destroyed. Processing, such as closing database connections, releasing file handles, etc.

  • Cooperation with other stages of the life cycle: The destruction callback is used in conjunction with other stages of the Spring life cycle (such as the initialization phase of the Bean), making the entire Bean life cycle management more complete. . You can ensure that any necessary cleanup operations are performed before the bean is destroyed.

  • Removal of dependencies: In the destruction callback, you can perform some cleanup operations related to dependencies to ensure that when the Bean is destroyed, the relevant dependencies are correct Dismiss to avoid memory leaks or other problems.

  • Resource recycling: Execute resource recycling logic in the destruction callback, such as releasing occupied system resources, closing network connections, etc., which helps to improve the resource utilization efficiency of the application.

  • Integration with frameworks or libraries: Some frameworks or libraries may need to be destroyed when the application is closed. Through Spring's destruction callback, you can easily integrate these Integrate the framework or library's destruction logic into your application.

  • Flexible configuration method: You can choose to use XML configuration, Java configuration or annotation to define the destruction callback, and choose according to personal or team preferences, providing flexibility .

  • Exception handling: If an exception occurs in the destruction callback, Spring will catch it and convert it to BeanDestructionException, thus preventing the application from closing normally , improving the security of the destruction process

Summarize

Lifecycle Callbacks are a powerful feature of the Spring framework, which provide developers with a flexible way to perform specific operations at different stages of a bean's life cycle. By destroying callbacks, we are able to better manage and control the components in our application. In actual development, reasonable use of life cycle callbacks can improve the stability and maintainability of applications.

Guess you like

Origin blog.csdn.net/yanyc0411/article/details/135027184