Spring中SmartLifecycle的用法解讀
Spring SmartLifecycle用法
Spring SmartLifecycle 在容器所有bean加載和初始化完畢執(zhí)行
在使用Spring開(kāi)發(fā)時(shí),我們都知道,所有bean都交給Spring容器來(lái)統(tǒng)一管理,其中包括每一個(gè)bean的加載和初始化。
有時(shí)候我們需要在Spring加載和初始化所有bean后,接著執(zhí)行一些任務(wù)或者啟動(dòng)需要的異步服務(wù),這樣我們可以使用 SmartLifecycle 來(lái)做到。
SmartLifecycle 是一個(gè)接口
當(dāng)Spring容器加載所有bean并完成初始化之后,會(huì)接著回調(diào)實(shí)現(xiàn)該接口的類(lèi)中對(duì)應(yīng)的方法(start()方法)。
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;
/**
* SmartLifecycle測(cè)試
*
*
*
*/
@Component
public class TestSmartLifecycle implements SmartLifecycle {
private boolean isRunning = false;
/**
* 1. 我們主要在該方法中啟動(dòng)任務(wù)或者其他異步服務(wù),比如開(kāi)啟MQ接收消息<br/>
* 2. 當(dāng)上下文被刷新(所有對(duì)象已被實(shí)例化和初始化之后)時(shí),將調(diào)用該方法,默認(rèn)生命周期處理器將檢查每個(gè)SmartLifecycle對(duì)象的isAutoStartup()方法返回的布爾值。
* 如果為“true”,則該方法會(huì)被調(diào)用,而不是等待顯式調(diào)用自己的start()方法。
*/
@Override
public void start() {
System.out.println("start");
// 執(zhí)行完其他業(yè)務(wù)后,可以修改 isRunning = true
isRunning = true;
}
/**
* 如果工程中有多個(gè)實(shí)現(xiàn)接口SmartLifecycle的類(lèi),則這些類(lèi)的start的執(zhí)行順序按getPhase方法返回值從小到大執(zhí)行。<br/>
* 例如:1比2先執(zhí)行,-1比0先執(zhí)行。 stop方法的執(zhí)行順序則相反,getPhase返回值較大類(lèi)的stop方法先被調(diào)用,小的后被調(diào)用。
*/
@Override
public int getPhase() {
// 默認(rèn)為0
return 0;
}
/**
* 根據(jù)該方法的返回值決定是否執(zhí)行start方法。<br/>
* 返回true時(shí)start方法會(huì)被自動(dòng)執(zhí)行,返回false則不會(huì)。
*/
@Override
public boolean isAutoStartup() {
// 默認(rèn)為false
return true;
}
/**
* 1. 只有該方法返回false時(shí),start方法才會(huì)被執(zhí)行。<br/>
* 2. 只有該方法返回true時(shí),stop(Runnable callback)或stop()方法才會(huì)被執(zhí)行。
*/
@Override
public boolean isRunning() {
// 默認(rèn)返回false
return isRunning;
}
/**
* SmartLifecycle子類(lèi)的才有的方法,當(dāng)isRunning方法返回true時(shí),該方法才會(huì)被調(diào)用。
*/
@Override
public void stop(Runnable callback) {
System.out.println("stop(Runnable)");
// 如果你讓isRunning返回true,需要執(zhí)行stop這個(gè)方法,那么就不要忘記調(diào)用callback.run()。
// 否則在你程序退出時(shí),Spring的DefaultLifecycleProcessor會(huì)認(rèn)為你這個(gè)TestSmartLifecycle沒(méi)有stop完成,程序會(huì)一直卡著結(jié)束不了,等待一定時(shí)間(默認(rèn)超時(shí)時(shí)間30秒)后才會(huì)自動(dòng)結(jié)束。
// PS:如果你想修改這個(gè)默認(rèn)超時(shí)時(shí)間,可以按下面思路做,當(dāng)然下面代碼是springmvc配置文件形式的參考,在SpringBoot中自然不是配置xml來(lái)完成,這里只是提供一種思路。
// <bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor">
// <!-- timeout value in milliseconds -->
// <property name="timeoutPerShutdownPhase" value="10000"/>
// </bean>
callback.run();
isRunning = false;
}
/**
* 接口Lifecycle的子類(lèi)的方法,只有非SmartLifecycle的子類(lèi)才會(huì)執(zhí)行該方法。<br/>
* 1. 該方法只對(duì)直接實(shí)現(xiàn)接口Lifecycle的類(lèi)才起作用,對(duì)實(shí)現(xiàn)SmartLifecycle接口的類(lèi)無(wú)效。<br/>
* 2. 方法stop()和方法stop(Runnable callback)的區(qū)別只在于,后者是SmartLifecycle子類(lèi)的專(zhuān)屬。
*/
@Override
public void stop() {
System.out.println("stop");
isRunning = false;
}
}
SmartLifecycle 解讀
org.springframework.context.SmartLifecycle解讀
1、接口定義
/**
* An extension of the {@link Lifecycle} interface for those objects that require to
* be started upon ApplicationContext refresh and/or shutdown in a particular order.
* The {@link #isAutoStartup()} return value indicates whether this object should
* be started at the time of a context refresh. The callback-accepting
* {@link #stop(Runnable)} method is useful for objects that have an asynchronous
* shutdown process. Any implementation of this interface <i>must</i> invoke the
* callback's run() method upon shutdown completion to avoid unnecessary delays
* in the overall ApplicationContext shutdown.
*
* <p>This interface extends {@link Phased}, and the {@link #getPhase()} method's
* return value indicates the phase within which this Lifecycle component should
* be started and stopped. The startup process begins with the <i>lowest</i>
* phase value and ends with the <i>highest</i> phase value (Integer.MIN_VALUE
* is the lowest possible, and Integer.MAX_VALUE is the highest possible). The
* shutdown process will apply the reverse order. Any components with the
* same value will be arbitrarily ordered within the same phase.
*
* <p>Example: if component B depends on component A having already started, then
* component A should have a lower phase value than component B. During the
* shutdown process, component B would be stopped before component A.
*
* <p>Any explicit "depends-on" relationship will take precedence over
* the phase order such that the dependent bean always starts after its
* dependency and always stops before its dependency.
*
* <p>Any Lifecycle components within the context that do not also implement
* SmartLifecycle will be treated as if they have a phase value of 0. That
* way a SmartLifecycle implementation may start before those Lifecycle
* components if it has a negative phase value, or it may start after
* those components if it has a positive phase value.
*
* <p>Note that, due to the auto-startup support in SmartLifecycle,
* a SmartLifecycle bean instance will get initialized on startup of the
* application context in any case. As a consequence, the bean definition
* lazy-init flag has very limited actual effect on SmartLifecycle beans.
*
* @author Mark Fisher
* @since 3.0
* @see LifecycleProcessor
* @see ConfigurableApplicationContext
*/
public interface SmartLifecycle extends Lifecycle, Phased {
/**
* Returns {@code true} if this {@code Lifecycle} component should get
* started automatically by the container at the time that the containing
* {@link ApplicationContext} gets refreshed.
* <p>A value of {@code false} indicates that the component is intended to
* be started through an explicit {@link #start()} call instead, analogous
* to a plain {@link Lifecycle} implementation.
* @see #start()
* @see #getPhase()
* @see LifecycleProcessor#onRefresh()
* @see ConfigurableApplicationContext#refresh()
*/
boolean isAutoStartup();
/**
* Indicates that a Lifecycle component must stop if it is currently running.
* <p>The provided callback is used by the {@link LifecycleProcessor} to support
* an ordered, and potentially concurrent, shutdown of all components having a
* common shutdown order value. The callback <b>must</b> be executed after
* the {@code SmartLifecycle} component does indeed stop.
* <p>The {@link LifecycleProcessor} will call <i>only</i> this variant of the
* {@code stop} method; i.e. {@link Lifecycle#stop()} will not be called for
* {@code SmartLifecycle} implementations unless explicitly delegated to within
* the implementation of this method.
* @see #stop()
* @see #getPhase()
*/
void stop(Runnable callback);
}
從注釋文檔里可以看出:
1、是接口 Lifecycle 的拓展,且會(huì)在應(yīng)用上下文類(lèi)ApplicationContext 執(zhí)行 refresh and/or shutdown 時(shí)會(huì)調(diào)用
2、方法 isAutoStartup() 返回的值會(huì)決定,當(dāng)前實(shí)體對(duì)象是否會(huì)被調(diào)用,當(dāng)應(yīng)用上下文類(lèi)ApplicationContext 執(zhí)行 refresh
3、stop(Runnable) 方法用于調(diào)用Lifecycle的stop方法
4、getPhase() 返回值用于設(shè)置LifeCycle的執(zhí)行優(yōu)先度:值越小優(yōu)先度越高
5、isRunning() 決定了start()方法的是否調(diào)用
2、應(yīng)用
public class SmartLifecycleImpl implements SmartLifecycle {
private Boolean isRunning = false;
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public void stop(Runnable callback) {
callback.run();
}
@Override
public void start() {
System.out.println("SmartLifecycleImpl is starting ....");
isRunning = true;
}
@Override
public void stop() {
System.out.println("SmartLifecycleImpl is stopped.");
}
/**
* 執(zhí)行start()方法前會(huì)用它來(lái)判斷是否執(zhí)行,返回為true時(shí),start()方法不執(zhí)行
*/
@Override
public boolean isRunning() {
return isRunning;
}
@Override
public int getPhase() {
return 0;
}
}
啟動(dòng)類(lèi)
public class ProviderBootstrap {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ProviderConfiguration.class);
context.start();
System.in.read();
}
@Configuration
static class ProviderConfiguration {
@Bean
public SmartLifecycleImpl getSmartLifecycleImpl(){
return new SmartLifecycleImpl();
}
}
}
可以發(fā)現(xiàn),類(lèi)SmartLifecycleImpl提交給spring容器后,啟動(dòng)后,會(huì)輸出 start() 方法的方法體。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
JVM?jstack實(shí)戰(zhàn)之死鎖問(wèn)題詳解
如果在生產(chǎn)環(huán)境發(fā)生了死鎖,我們將看到的是部署的程序沒(méi)有任何反應(yīng)了,這個(gè)時(shí)候我們可以借助?jstack進(jìn)行分析,下面我們實(shí)戰(zhàn)操作查找死鎖的原因2022-10-10
servlet監(jiān)聽(tīng)實(shí)現(xiàn)統(tǒng)計(jì)在線人數(shù)功能 附源碼下載
這篇文章主要為大家詳細(xì)介紹了servlet監(jiān)聽(tīng)統(tǒng)計(jì)在線人數(shù)的實(shí)現(xiàn)方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04
springboot 實(shí)現(xiàn)bean手動(dòng)注入操作
這篇文章主要介紹了springboot 實(shí)現(xiàn)bean手動(dòng)注入操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-01-01
Java中StringBuilder類(lèi)的介紹與常用方法
StringBuilder是一個(gè)可變的字符串的操作類(lèi),我們可以把它看成是一個(gè)對(duì)象容器,下面這篇文章主要給大家介紹了關(guān)于Java中StringBuilder類(lèi)的介紹與常用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12
feign調(diào)用返回object類(lèi)型轉(zhuǎn)換方式
這篇文章主要介紹了feign調(diào)用返回object類(lèi)型轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
java樹(shù)結(jié)構(gòu)stream工具類(lèi)的示例代碼詳解
Stream 作為 Java 8 的一大亮點(diǎn),它與 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念。今天通過(guò)本文重點(diǎn)給大家介紹java樹(shù)結(jié)構(gòu)stream工具類(lèi)的示例代碼,感興趣的朋友一起看看吧2022-03-03
被kafka-client和springkafka版本坑到自閉及解決
這篇文章主要介紹了被kafka-client和springkafka版本坑到自閉及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
Activiti如何動(dòng)態(tài)獲取流程圖過(guò)程詳解
這篇文章主要介紹了Activiti如何動(dòng)態(tài)獲取流程圖過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03

