您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)Spring中SmartLifecycle的用法是怎樣的,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲!
Spring SmartLifecycle 在容器所有bean加載和初始化完畢執(zhí)行
在使用Spring開發(fā)時(shí),我們都知道,所有bean都交給Spring容器來統(tǒng)一管理,其中包括每一個(gè)bean的加載和初始化。
有時(shí)候我們需要在Spring加載和初始化所有bean后,接著執(zhí)行一些任務(wù)或者啟動(dòng)需要的異步服務(wù),這樣我們可以使用 SmartLifecycle 來做到。
當(dāng)Spring容器加載所有bean并完成初始化之后,會(huì)接著回調(diào)實(shí)現(xiàn)該接口的類中對(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ù),比如開啟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的類,則這些類的start的執(zhí)行順序按getPhase方法返回值從小到大執(zhí)行。<br/> * 例如:1比2先執(zhí)行,-1比0先執(zhí)行。 stop方法的執(zhí)行順序則相反,getPhase返回值較大類的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子類的才有的方法,當(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沒有stop完成,程序會(huì)一直卡著結(jié)束不了,等待一定時(shí)間(默認(rèn)超時(shí)時(shí)間30秒)后才會(huì)自動(dòng)結(jié)束。 // PS:如果你想修改這個(gè)默認(rèn)超時(shí)時(shí)間,可以按下面思路做,當(dāng)然下面代碼是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的子類才會(huì)執(zhí)行該方法。<br/> * 1. 該方法只對(duì)直接實(shí)現(xiàn)接口Lifecycle的類才起作用,對(duì)實(shí)現(xiàn)SmartLifecycle接口的類無效。<br/> * 2. 方法stop()和方法stop(Runnable callback)的區(qū)別只在于,后者是SmartLifecycle子類的專屬。 */ @Override public void stop() { System.out.println("stop"); isRunning = false; } }
org.springframework.context.SmartLifecycle解讀
/** * 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)用上下文類ApplicationContext 執(zhí)行 refresh and/or shutdown 時(shí)會(huì)調(diào)用
2、方法 isAutoStartup() 返回的值會(huì)決定,當(dāng)前實(shí)體對(duì)象是否會(huì)被調(diào)用,當(dāng)應(yīng)用上下文類ApplicationContext 執(zhí)行 refresh
3、stop(Runnable) 方法用于調(diào)用Lifecycle的stop方法
4、getPhase() 返回值用于設(shè)置LifeCycle的執(zhí)行優(yōu)先度:值越小優(yōu)先度越高
5、isRunning() 決定了start()方法的是否調(diào)用
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ì)用它來判斷是否執(zhí)行,返回為true時(shí),start()方法不執(zhí)行 */ @Override public boolean isRunning() { return isRunning; } @Override public int getPhase() { return 0; } }
啟動(dòng)類
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),類SmartLifecycleImpl提交給spring容器后,啟動(dòng)后,會(huì)輸出 start() 方法的方法體。
上述就是小編為大家分享的Spring中SmartLifecycle的用法是怎樣的了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。