玩转Spring生命周期之Lifecycle

要与容器的bean生命周期管理交互,即容器在启动后和容器在销毁前对每个bean执行操作,有如下三种方法:

1.实现Spring框架的InitializingBeanDisposableBean接口。容器为前者调用afterPropertiesSet()方法,为后者调用destroy()方法,以允许bean在初始化和销毁bean时执行某些操作。

public class HelloLifeCycle implements InitializingBean, DisposableBean {
    
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet 启动");
    }

    public void destroy() throws Exception {
        System.out.println("DisposableBean 停止");
    }
}

2.bean自定义初始化方法和销毁方法,然后在定义bean时指定初始化方法和销毁方法

 <bean id="helloLifeCycle" class="com.hzways.life.cycle.HelloLifeCycle" init-method="init3" destroy-method="destroy3"/>
3.JSR-250 @PostConstruct和@PreDestroy注解通常被认为是在现代Spring应用程序中接PostConstruct注解用于方法上,该方法在初始化的依赖注入操作之后被执行。这个方法必须在class被放到service之后被执行,这个注解所在的类必须支持依赖注入。
public class HelloLifeCycle {

    @PostConstruct
    private void init2() {
        System.out.println("PostConstruct 启动");
    }

    @PreDestroy
    private void destroy2() {
        System.out.println("PreDestroy 停止");
    }

}

PostConstruct注解用于方法上,该方法在初始化的依赖注入操作之后被执行。因此,容器必须要开启支持注解形式的依赖注入的功能,加入如下配置即可:

 <context:annotation-config/>

在使用Spring开发时,我们都知道,所有bean都交给Spring容器来统一管理,其中包括没一个bean的加载和初始化。
有时候我们需要在Spring加载和初始化所有bean后,接着执行一些任务或者启动需要的异步服务,这样我们可以使用 SmartLifecycle 来做到。

import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;
@Component
public class TestSmartLifecycle implements SmartLifecycle {

    private boolean isRunning = false;
    /**
     * 1. 我们主要在该方法中启动任务或者其他异步服务,比如开启MQ接收消息<br/>
     * 2. 当上下文被刷新(所有对象已被实例化和初始化之后)时,将调用该方法,默认生命周期处理器将检查每个SmartLifecycle对象的isAutoStartup()方法返回的布尔值。
     * 如果为“true”,则该方法会被调用,而不是等待显式调用自己的start()方法。
     */
    @Override
    public void start() {
        System.out.println("start");
        // 执行完其他业务后,可以修改 isRunning = true
        isRunning = true;
    }

    /**
     * 如果工程中有多个实现接口SmartLifecycle的类,则这些类的start的执行顺序按getPhase方法返回值从小到大执行。<br/>
     * 例如:1比2先执行,-1比0先执行。 stop方法的执行顺序则相反,getPhase返回值较大类的stop方法先被调用,小的后被调用。
     */
    @Override
    public int getPhase() {
        // 默认为0
        return 0;
    }
    /**
     * 根据该方法的返回值决定是否执行start方法。<br/> 
     * 返回true时start方法会被自动执行,返回false则不会。
     */
    @Override
    public boolean isAutoStartup() {
        // 默认为false
        return true;
    }

    /**
     * 1. 只有该方法返回false时,start方法才会被执行。<br/>
     * 2. 只有该方法返回true时,stop(Runnable callback)或stop()方法才会被执行。
     */
    @Override
    public boolean isRunning() {
        // 默认返回false
        return isRunning;
    }

    /**
     * SmartLifecycle子类的才有的方法,当isRunning方法返回true时,该方法才会被调用。
     */
    @Override
    public void stop(Runnable callback) {
        System.out.println("stop(Runnable)");

        // 如果你让isRunning返回true,需要执行stop这个方法,那么就不要忘记调用callback.run()。
        // 否则在你程序退出时,Spring的DefaultLifecycleProcessor会认为你这个TestSmartLifecycle没有stop完成,程序会一直卡着结束不了,等待一定时间(默认超时时间30秒)后才会自动结束。
        // PS:如果你想修改这个默认超时时间,可以按下面思路做,当然下面代码是springmvc配置文件形式的参考,在SpringBoot中自然不是配置xml来完成,这里只是提供一种思路。
        // <bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor">
        //      <!-- timeout value in milliseconds -->
        //      <property name="timeoutPerShutdownPhase" value="10000"/>
        // </bean>
        callback.run();

        isRunning = false;
    }

    /**
     * 接口Lifecycle的子类的方法,只有非SmartLifecycle的子类才会执行该方法。<br/>
     * 1. 该方法只对直接实现接口Lifecycle的类才起作用,对实现SmartLifecycle接口的类无效。<br/>
     * 2. 方法stop()和方法stop(Runnable callback)的区别只在于,后者是SmartLifecycle子类的专属。
     */
    @Override
    public void stop() {
        System.out.println("stop");

        isRunning = false;
    }
}

猜你喜欢

转载自www.cnblogs.com/deityjian/p/11296846.html