Spring中SmartLifecycle的用法解讀

Spring SmartLifecycle用法

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

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

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

SmartLifecycle 是一個接口

當Spring容器加載所有bean並完成初始化之後,會接著回調實現該接口的類中對應的方法(start()方法)。

import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;
/**
 * SmartLifecycle測試
 *
 * 
 * 
 */
@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;
    }
}

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 的拓展,且會在應用上下文類ApplicationContext 執行 refresh and/or shutdown 時會調用

2、方法 isAutoStartup() 返回的值會決定,當前實體對象是否會被調用,當應用上下文類ApplicationContext 執行 refresh

3、stop(Runnable) 方法用於調用Lifecycle的stop方法

4、getPhase() 返回值用於設置LifeCycle的執行優先度:值越小優先度越高

5、isRunning() 決定瞭start()方法的是否調用

2、應用

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.");
    }
    /**
     * 執行start()方法前會用它來判斷是否執行,返回為true時,start()方法不執行
     */
    @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();
        }
    }
}

可以發現,類SmartLifecycleImpl提交給spring容器後,啟動後,會輸出 start() 方法的方法體。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: