最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring中SmartLifecycle的用法解讀

 更新時間:2021年09月24日 11:21:42   作者:shuaidong  
這篇文章主要介紹了Spring中SmartLifecycle的用法解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Spring SmartLifecycle用法

Spring SmartLifecycle 在容器所有bean加載和初始化完畢執(zhí)行

在使用Spring開發(fā)時,我們都知道,所有bean都交給Spring容器來統(tǒng)一管理,其中包括每一個bean的加載和初始化。

有時候我們需要在Spring加載和初始化所有bean后,接著執(zhí)行一些任務(wù)或者啟動需要的異步服務(wù),這樣我們可以使用 SmartLifecycle 來做到。

SmartLifecycle 是一個接口

當(dāng)Spring容器加載所有bean并完成初始化之后,會接著回調(diào)實現(xiàn)該接口的類中對應(yīng)的方法(start()方法)。

import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;
/**
 * SmartLifecycle測試
 *
 * 
 * 
 */
@Component
public class TestSmartLifecycle implements SmartLifecycle {
    private boolean isRunning = false;
    /**
     * 1. 我們主要在該方法中啟動任務(wù)或者其他異步服務(wù),比如開啟MQ接收消息<br/>
     * 2. 當(dāng)上下文被刷新(所有對象已被實例化和初始化之后)時,將調(diào)用該方法,默認(rèn)生命周期處理器將檢查每個SmartLifecycle對象的isAutoStartup()方法返回的布爾值。
     * 如果為“true”,則該方法會被調(diào)用,而不是等待顯式調(diào)用自己的start()方法。
     */
    @Override
    public void start() {
        System.out.println("start");
        // 執(zhí)行完其他業(yè)務(wù)后,可以修改 isRunning = true
        isRunning = true;
    }
    /**
     * 如果工程中有多個實現(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時start方法會被自動執(zhí)行,返回false則不會。
     */
    @Override
    public boolean isAutoStartup() {
        // 默認(rèn)為false
        return true;
    }
    /**
     * 1. 只有該方法返回false時,start方法才會被執(zhí)行。<br/>
     * 2. 只有該方法返回true時,stop(Runnable callback)或stop()方法才會被執(zhí)行。
     */
    @Override
    public boolean isRunning() {
        // 默認(rèn)返回false
        return isRunning;
    }
    /**
     * SmartLifecycle子類的才有的方法,當(dāng)isRunning方法返回true時,該方法才會被調(diào)用。
     */
    @Override
    public void stop(Runnable callback) {
        System.out.println("stop(Runnable)");
        // 如果你讓isRunning返回true,需要執(zhí)行stop這個方法,那么就不要忘記調(diào)用callback.run()。
        // 否則在你程序退出時,Spring的DefaultLifecycleProcessor會認(rèn)為你這個TestSmartLifecycle沒有stop完成,程序會一直卡著結(jié)束不了,等待一定時間(默認(rèn)超時時間30秒)后才會自動結(jié)束。
        // PS:如果你想修改這個默認(rèn)超時時間,可以按下面思路做,當(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的子類才會執(zhí)行該方法。<br/>
     * 1. 該方法只對直接實現(xiàn)接口Lifecycle的類才起作用,對實現(xiàn)SmartLifecycle接口的類無效。<br/>
     * 2. 方法stop()和方法stop(Runnable callback)的區(qū)別只在于,后者是SmartLifecycle子類的專屬。
     */
    @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 的拓展,且會在應(yīng)用上下文類ApplicationContext 執(zhí)行 refresh and/or shutdown 時會調(diào)用

2、方法 isAutoStartup() 返回的值會決定,當(dāng)前實體對象是否會被調(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)用

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()方法前會用它來判斷是否執(zhí)行,返回為true時,start()方法不執(zhí)行
     */
    @Override
    public boolean isRunning() {
        return isRunning;
    }
 
    @Override
    public int getPhase() {
        return 0;
    }
}

啟動類

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容器后,啟動后,會輸出 start() 方法的方法體。

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • @FeignClient之name,value,url詳解

    @FeignClient之name,value,url詳解

    在FeignClient中,`name`用于指定服務(wù)的名稱,通常與服務(wù)注冊中心中的服務(wù)名關(guān)聯(lián),而`url`用于指定請求的基礎(chǔ)URL,適用于不使用服務(wù)注冊的場景,如果同時配置了`name`和`url`,則`url`會優(yōu)先生效,Feign會直接使用`url`指定的地址
    2024-11-11
  • Java 圖片壓縮實現(xiàn)思路及代碼

    Java 圖片壓縮實現(xiàn)思路及代碼

    本文為大家詳細(xì)介紹下圖片壓縮的具體實現(xiàn)思路及java代碼,想學(xué)習(xí)的各位可以參考下哈,希望對大家有所幫助
    2013-07-07
  • 詳解Java網(wǎng)絡(luò)編程

    詳解Java網(wǎng)絡(luò)編程

    網(wǎng)絡(luò)編程是指編寫運(yùn)行在多個設(shè)備(計算機(jī))的程序,這些設(shè)備都通過網(wǎng)絡(luò)連接起來。本文介紹了一些網(wǎng)絡(luò)編程基礎(chǔ)的概念,并用Java來實現(xiàn)TCP和UDP的Socket的編程,來讓讀者更好的了解其原理
    2021-06-06
  • 最新評論

    黑山县| 湾仔区| 海门市| 宁德市| 台湾省| 辰溪县| 灵石县| 鹰潭市| 凌云县| 江口县| 房山区| 铜鼓县| 荔浦县| 万山特区| 武城县| 湘乡市| 眉山市| 城固县| 神木县| 甘德县| 嘉禾县| 伊春市| 南投县| 郯城县| 五寨县| 西充县| 和田县| 如东县| 从化市| 铁岭县| 贵阳市| 迁西县| 大安市| 长寿区| 榆中县| 襄垣县| 托克托县| 浏阳市| 冕宁县| 盐源县| 鱼台县|