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

Spring中的Lifecycle接口使用與源碼分析

 更新時(shí)間:2023年05月12日 09:00:47   作者:morris131  
這篇文章主要介紹了Spring中的Lifecycle接口使用與源碼分析,LifeCycle接口定義了Spring容器的生命周期,任何被Spring管理的對(duì)象都可以實(shí)現(xiàn)該接口,需要的朋友可以參考下

LifeCycle接口定義了Spring容器的生命周期,任何被Spring管理的對(duì)象都可以實(shí)現(xiàn)該接口。當(dāng)Spring容器本身啟動(dòng)和停止時(shí),會(huì)回調(diào)LifeCycle接口中定義的方法。

Lifecycle接口的聲明

org.springframework.context.Lifecycle

public interface Lifecycle {
	    /**
     * 啟動(dòng)當(dāng)前組件,如果組件已經(jīng)在運(yùn)行,不應(yīng)該拋出異常,這樣將開(kāi)始信號(hào)傳播到應(yīng)用的所有組件中去。
     */
	void start();
	    /**
     * 通常以同步方式停止該組件,當(dāng)該方法執(zhí)行完成后,該組件會(huì)被完全停止。當(dāng)需要異步停止行為時(shí),考慮實(shí)現(xiàn)SmartLifecycle和它的 stop(Runnable) 方法變體。 
	 注意,此停止通知在銷毀前不能保證到達(dá):
    在常規(guī)關(guān)閉時(shí),{@code Lifecycle} bean將首先收到一個(gè)停止通知,然后才傳播常規(guī)銷毀回調(diào);
    在上下文的生命周期內(nèi)的刷新或中止時(shí),只調(diào)用銷毀方法
    對(duì)于容器,這將把停止信號(hào)傳播到應(yīng)用的所有組件
     */
	void stop();
	    /**
      *  檢查此組件是否正在運(yùn)行。
      *  1. 只有該方法返回false時(shí),start方法才會(huì)被執(zhí)行。
      *  2. 只有該方法返回true時(shí),stop(Runnable callback)或stop()方法才會(huì)被執(zhí)行。
      */
	boolean isRunning();
}

Lifecycle的使用

自定義一個(gè)Lifecycle需要實(shí)現(xiàn)Lifecycle接口:

package com.morris.spring.demo.lifecycle;
import org.springframework.context.Lifecycle;
/**
 * 自定義Lifecycle
 */
public class MyLifecycle implements Lifecycle {
	private boolean isRunning;
	@Override
	public void start() {
		System.out.println("MyLifecycle start");
		isRunning = true;
	}
	@Override
	public void stop() {
		System.out.println("MyLifecycle stop");
		isRunning = false;
	}
	@Override
	public boolean isRunning() {
		return isRunning;
	}
}

測(cè)試類:

public class LifecycleDemo {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
		applicationContext.register(MyLifecycle.class);
		applicationContext.refresh();
	}
}

啟動(dòng)main()方法后發(fā)現(xiàn)并沒(méi)有調(diào)用MyLifecycle的start()和stop()方法。

把測(cè)試類改為如下,主動(dòng)調(diào)用applicationContext容器的start()和stop()方法:

public class LifecycleDemo {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
		applicationContext.register(MyLifecycle.class);
		applicationContext.refresh();
		applicationContext.start();
		applicationContext.stop();
	}
}

運(yùn)行結(jié)果如下:

DEBUG main DefaultLifecycleProcessor:356 - Starting beans in phase 0
MyLifecycle start
DEBUG main DefaultLifecycleProcessor:188 - Successfully started bean 'myLifecycle'
DEBUG main DefaultLifecycleProcessor:369 - Stopping beans in phase 0
MyLifecycle stop
DEBUG main DefaultLifecycleProcessor:253 - Successfully stopped bean 'myLifecycle'

這時(shí)我們看到Spring容器回調(diào)了Lifecycle生命周期的方法。

SmartLifecycle接口的聲明

常規(guī)的LifeCycle接口只能在容器上下文顯式的調(diào)用start()或stop()方法時(shí),才會(huì)去回調(diào)LifeCycle的實(shí)現(xiàn)類的start()或stop()方法邏輯,并不意味著在容器上下文刷新時(shí)自動(dòng)回調(diào)。

org.springframework.context.SmartLifecycle

public interface SmartLifecycle extends Lifecycle, Phased {
	int DEFAULT_PHASE = Integer.MAX_VALUE;
	/**
      * 如果該`Lifecycle`類所在的上下文在調(diào)用`refresh`時(shí),希望能夠自己自動(dòng)進(jìn)行回調(diào),則返回`true`* ,
      * false的值表明組件打算通過(guò)顯式的start()調(diào)用來(lái)啟動(dòng),類似于普通的Lifecycle實(shí)現(xiàn)。
     */
	default boolean isAutoStartup() {
		return true;
	}
	default void stop(Runnable callback) {
		stop();
		callback.run();
	}
	@Override
	default int getPhase() {
		return DEFAULT_PHASE;
	}
}

SmartLifecycle的使用

自定義SmartLifecycle需要實(shí)現(xiàn)SmartLifecycle接口:

package com.morris.spring.demo.lifecycle;
import org.springframework.context.SmartLifecycle;
/**
 * 自定義SmartLifecycle
 */
public class MySmartLifecycle implements SmartLifecycle {
	private boolean isRunning;
	@Override
	public void start() {
		System.out.println("MyLifecycle start");
		isRunning = true;
	}
	@Override
	public void stop() {
		System.out.println("MyLifecycle stop");
		isRunning = false;
	}
	@Override
	public boolean isRunning() {
		return isRunning;
	}
}

測(cè)試類:

package com.morris.spring.demo.lifecycle;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
 * 演示SmartLifecycle
 */
public class SmartLifecycleDemo {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
		applicationContext.register(MySmartLifecycle.class);
		applicationContext.refresh();
	}
}

運(yùn)行結(jié)果如下:

DEBUG main DefaultListableBeanFactory:228 - Creating shared instance of singleton bean 'mySmartLifecycle'
DEBUG main DefaultLifecycleProcessor:357 - Starting beans in phase 2147483647
MyLifecycle start
DEBUG main DefaultLifecycleProcessor:189 - Successfully started bean 'mySmartLifecycle'

容器中多個(gè)實(shí)現(xiàn)了Lifecycle的類如果希望有順序的進(jìn)行回調(diào)時(shí),那么啟動(dòng)和關(guān)閉調(diào)用的順序可能很重要。如果任何兩個(gè)對(duì)象之間存在依賴關(guān)系,那么依賴方將在依賴后開(kāi)始,在依賴前停止。然而,有時(shí)直接依賴關(guān)系是未知的。您可能只知道某個(gè)類型的對(duì)象應(yīng)該在另一個(gè)類型的對(duì)象之前開(kāi)始。在這些情況下,SmartLifecycle接口定義了另一個(gè)選項(xiàng),即在其超接口上定義的getPhase()方法。

當(dāng)開(kāi)始時(shí),getPhase()返回值最小的對(duì)象先開(kāi)始,當(dāng)停止時(shí),遵循相反的順序。因此,實(shí)現(xiàn)SmartLifecycle的對(duì)象及其getPhase()方法返回Integer.MIN_VALUE將在第一個(gè)開(kāi)始和最后一個(gè)停止。相反,MAX_VALUE將指示對(duì)象應(yīng)該在最后啟動(dòng)并首先停止。

源碼解讀

Lifecycle的調(diào)用時(shí)機(jī)

Lifecycle中的方法只有在主動(dòng)調(diào)用容器的start()和stop()方法時(shí)才會(huì)觸發(fā),所以直接看容器的start()或stop()方法即可。

org.springframework.context.support.AbstractApplicationContext#start

public void start() {
	// 獲取DefaultLifecycleProcessor
	/**
		 * @see DefaultLifecycleProcessor#start()
		 */
	getLifecycleProcessor().start();
	publishEvent(new ContextStartedEvent(this));
}

org.springframework.context.support.DefaultLifecycleProcessor#start

public void start() {
	startBeans(false);
	this.running = true;
}

最后會(huì)調(diào)用DefaultLifecycleProcessor的startBeans()方法。

SmartLifecycle的調(diào)用時(shí)機(jī)

SmartLifecycle的調(diào)用時(shí)機(jī)發(fā)生在容器refresh()時(shí)。

org.springframework.context.support.AbstractApplicationContext#finishRefresh

protected void finishRefresh() {
	// Clear context-level resource caches (such as ASM metadata from scanning).
	clearResourceCaches();
	// Initialize lifecycle processor for this context.
	// 注入DefaultLifecycleProcessor
	initLifecycleProcessor();
	// Propagate refresh to lifecycle processor first.
	getLifecycleProcessor().onRefresh();
	// Publish the final event.
	publishEvent(new ContextRefreshedEvent(this));
	// Participate in LiveBeansView MBean, if active.
	LiveBeansView.registerApplicationContext(this);
}

DefaultLifecycleProcessor的創(chuàng)建并調(diào)用onRefresh()方法。

org.springframework.context.support.DefaultLifecycleProcessor#onRefresh

public void onRefresh() {
	startBeans(true);
	this.running = true;
}

通用最后會(huì)調(diào)用DefaultLifecycleProcessor的startBeans()方法,只不過(guò)參數(shù)傳入true。

DefaultLifecycleProcessor.startBeans()

private void startBeans(boolean autoStartupOnly) {
	// 拿到容器中所有的Lifecycle
	Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
	Map<Integer, LifecycleGroup> phases = new HashMap<>();
	lifecycleBeans.forEach((beanName, bean) -> {
		if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
			// autoStartupOnly=false,表示調(diào)用的Lifecycle
			// autoStartupOnly=true,表示調(diào)用的SmartLifecycle
			int phase = getPhase(bean);
			// 根據(jù)phase進(jìn)行分組
			LifecycleGroup group = phases.get(phase);
			if (group == null) {
				group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
				phases.put(phase, group);
			}
			group.add(beanName, bean);
		}
	});
	if (!phases.isEmpty()) {
		List<Integer> keys = new ArrayList<>(phases.keySet());
		Collections.sort(keys);
		for (Integer key : keys) {
			// 調(diào)用start()
			phases.get(key).start();
		}
	}
}

到此這篇關(guān)于Spring中的Lifecycle接口使用與源碼分析的文章就介紹到這了,更多相關(guān)Spring中的Lifecycle接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 詳解Spring Boot自動(dòng)裝配的方法步驟

    詳解Spring Boot自動(dòng)裝配的方法步驟

    這篇文章主要介紹了詳解Spring Boot自動(dòng)裝配的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • IDEA中Maven報(bào)錯(cuò)Cannot resolve xxx的解決方法匯總(親測(cè)有效)

    IDEA中Maven報(bào)錯(cuò)Cannot resolve xxx的解決方法匯總(親測(cè)有效)

    在IDEA中的pom文件中添加了依賴,并且正確加載了相應(yīng)依賴,pom文件沒(méi)有報(bào)紅,看起來(lái)像是把所有依賴庫(kù)全部加載進(jìn)來(lái)了,但是代碼中使用依賴的類庫(kù)使報(bào)紅,本文給大家介紹了IDEA中Maven報(bào)錯(cuò)Cannot resolve xxx的解決方法匯總,需要的朋友可以參考下
    2024-06-06
  • Lombok在idea中的使用教程

    Lombok在idea中的使用教程

    Lombok是一個(gè)可以通過(guò)簡(jiǎn)單的注解形式,來(lái)幫助我們簡(jiǎn)化消除一些必須有但顯得很臃腫(如果getter、setter方法)的Java代碼的工具,通過(guò)使用對(duì)應(yīng)的注解,可以在編譯源碼的時(shí)候生成對(duì)應(yīng)的方法,這篇文章主要介紹了Lombok在idea中的使用,需要的朋友可以參考下
    2023-03-03
  • 聊聊springboot靜態(tài)資源加載的規(guī)則

    聊聊springboot靜態(tài)資源加載的規(guī)則

    這篇文章主要介紹了springboot靜態(tài)資源加載的規(guī)則,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • 強(qiáng)烈推薦IDEA提高開(kāi)發(fā)效率的必備插件

    強(qiáng)烈推薦IDEA提高開(kāi)發(fā)效率的必備插件

    這篇文章主要介紹了強(qiáng)烈推薦IDEA提高開(kāi)發(fā)效率的必備插件,文中有非常詳細(xì)的圖文示例,對(duì)想要提高企業(yè)開(kāi)發(fā)效率的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-04-04
  • 在IDEA使用中directory和package的操作

    在IDEA使用中directory和package的操作

    這篇文章主要介紹了在IDEA使用中directory和package的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-02-02
  • SpringBoot3.3.X整合Mybatis-Plus的實(shí)現(xiàn)示例

    SpringBoot3.3.X整合Mybatis-Plus的實(shí)現(xiàn)示例

    本文介紹了在Spring Boot 3.3.2中整合MyBatis-Plus 3.5.7,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2025-03-03
  • Java中的Timer與TimerTask源碼及使用解析

    Java中的Timer與TimerTask源碼及使用解析

    這篇文章主要介紹了Java中的Timer與TimerTask源碼及使用解析,在Java中,經(jīng)常使用Timer來(lái)定時(shí)調(diào)度任務(wù),Timer調(diào)度任務(wù)有一次性調(diào)度和循環(huán)調(diào)度,循環(huán)調(diào)度有分為固定速率調(diào)度(fixRate)和固定時(shí)延調(diào)度(fixDelay),需要的朋友可以參考下
    2023-10-10
  • Java源碼難點(diǎn)突破Lambda表達(dá)式執(zhí)行原理

    Java源碼難點(diǎn)突破Lambda表達(dá)式執(zhí)行原理

    這篇文章主要為大家介紹了Java難點(diǎn)突破Lambda表達(dá)式執(zhí)行原理分析及示例的實(shí)現(xiàn)源碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2022-03-03
  • Mybatis-Plus實(shí)現(xiàn)公共字段自動(dòng)賦值的方法

    Mybatis-Plus實(shí)現(xiàn)公共字段自動(dòng)賦值的方法

    這篇文章主要介紹了Mybatis-Plus實(shí)現(xiàn)公共字段自動(dòng)賦值的方法,涉及到通用字段自動(dòng)填充的最佳實(shí)踐總結(jié),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-07-07

最新評(píng)論

博野县| 屯昌县| 南雄市| 达拉特旗| 大石桥市| 绵阳市| 大连市| 锦州市| 长宁区| 曲阜市| 贵德县| 太白县| 古浪县| 紫阳县| 玛沁县| 泾源县| 剑川县| 西华县| 临澧县| 玉山县| 克东县| 紫云| 什邡市| 肇东市| 科尔| 临武县| 津南区| 武宁县| 融水| 渝中区| 如东县| 合山市| 建平县| 汕尾市| 勐海县| 苏尼特左旗| 广水市| 东城区| 大石桥市| 卓尼县| 石楼县|