主要是實現smartLifecycle類
package com.ruoyi.workflow.util;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;@Component
public class MyShutdownHook implements SmartLifecycle {@Autowiredprivate ApplicationContext applicationContext;private boolean isRunning = false;/*** 1. 我們主要在該方法中啟動任務或者其他異步服務,比如開啟MQ接收消息<br/>* 2. 當上下文被刷新(所有對象已被實例化和初始化之后)時,將調用該方法,默認生命周期處理器將檢查每個SmartLifecycle對象的isAutoStartup()方法返回的布爾值。* 如果為“true”,則該方法會被調用,而不是等待顯式調用自己的start()方法。*/@Overridepublic void start() {System.out.println("start");
// 獲取配置文件中的值String configValue =applicationContext.getEnvironment().getProperty("name");System.err.println("開始了完美的一天"+configValue);// 執行完其他業務后,可以修改 isRunning = trueisRunning = true;}/*** 如果工程中有多個實現接口SmartLifecycle的類,則這些類的start的執行順序按getPhase方法返回值從小到大執行。<br/>* 例如:1比2先執行,-1比0先執行。 stop方法的執行順序則相反,getPhase返回值較大類的stop方法先被調用,小的后被調用。*/@Overridepublic int getPhase() {// 默認為0return 0;}/*** 根據該方法的返回值決定是否執行start方法。<br/> * 返回true時start方法會被自動執行,返回false則不會。*/@Overridepublic boolean isAutoStartup() {// 默認為falsereturn true;}/*** 1. 只有該方法返回false時,start方法才會被執行。<br/>* 2. 只有該方法返回true時,stop(Runnable callback)或stop()方法才會被執行。*/@Overridepublic boolean isRunning() {// 默認返回falsereturn isRunning;}/*** SmartLifecycle子類的才有的方法,當isRunning方法返回true時,該方法才會被調用。*/@Overridepublic 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子類的專屬。*/@Overridepublic void stop() {System.out.println("stop");isRunning = false;}
}