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

Spring中SmartLifecycle和Lifecycle的作用和區(qū)別

 更新時(shí)間:2021年03月10日 09:01:16   作者:brucelwl  
這篇文章主要介紹了Spring中SmartLifecycle和Lifecycle的作用和區(qū)別,本文通過實(shí)例代碼給大家介紹的非常詳細(xì)對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

本文基于SpringBoot 2.5.0-M2講解Spring中LifecycleSmartLifecycle的作用和區(qū)別,以及如何控制SmartLifecycle的優(yōu)先級(jí)。
并講解SpringBoot中如何通過SmartLifecycle來啟動(dòng)/停止web容器.

 SmartLifecycle和Lifecycle作用

都是讓開發(fā)者可以在所有的bean都創(chuàng)建完成(getBean) 之后執(zhí)行自己的初始化工作,或者在退出時(shí)執(zhí)行資源銷毀工作。

SmartLifecycle和Lifecycle區(qū)別

 1.SmartLifecycle接口繼承Lifecycle接口,同時(shí)繼承了org.springframework.context.Phased接口用于控制多個(gè)SmartLifecycle實(shí)現(xiàn)之間的優(yōu)先級(jí)。

2.在SpringBoot應(yīng)用中,或在Spring應(yīng)用中沒有調(diào)用AbstractApplicationContext#start方法,如果一個(gè)Bean只是實(shí)現(xiàn)了Lifecycle接口的情況下:

不會(huì)執(zhí)行Lifecycle接口中的啟動(dòng)方法,包括Lifecycle#isRunning方法也不會(huì)被執(zhí)行。

但是在應(yīng)用 退出時(shí) 會(huì)執(zhí)行Lifecycle#isRunning方法判斷該Lifecycle是否已經(jīng)啟動(dòng),如果返回true則調(diào)用Lifecycle#stop()停止方法。

3. 如果一個(gè)Bean實(shí)現(xiàn)了SmartLifecycle接口,則會(huì)執(zhí)行啟動(dòng)方法。先會(huì)被根據(jù)Phased接口優(yōu)先級(jí)分組,封裝在LifecycleGroup,然后循環(huán)調(diào)用LifecycleGroup#start()方法,SmartLifecycle#isRunning判斷是否已經(jīng)執(zhí)行,返回false表示還未執(zhí)行,則調(diào)用SmartLifecycle#start()執(zhí)行。Phased返回值越小,優(yōu)先級(jí)越高。

4.SmartLifecycle中還有個(gè)isAutoStartup方法,如果返回false,在啟動(dòng)時(shí)也不會(huì)執(zhí)行start方法,默認(rèn)返回true

源碼分析

SmartLifecycleLifecycle都是在org.springframework.context.support.DefaultLifecycleProcessor中被調(diào)用,
DefaultLifecycleProcessor#onRefresh方法在執(zhí)行AbstractApplicationContext#finishRefresh時(shí)會(huì)被調(diào)用,調(diào)用棧如下:

startBeans:142, DefaultLifecycleProcessor (org.springframework.context.support)
onRefresh:123, DefaultLifecycleProcessor (org.springframework.context.support)
finishRefresh:934, AbstractApplicationContext (org.springframework.context.support)
refresh:585, AbstractApplicationContext (org.springframework.context.support)
refresh:144, ServletWebServerApplicationContext (org.springframework.boot.web.servlet.context)
refresh:755, SpringApplication (org.springframework.boot)
refreshContext:426, SpringApplication (org.springframework.boot)
run:326, SpringApplication (org.springframework.boot)
run:1299, SpringApplication (org.springframework.boot)
run:1288, SpringApplication (org.springframework.boot)
main:31, DemoApplication (com.example.demo)

DefaultLifecycleProcessor#onRefresh源碼:

@Override
public void onRefresh() {
	startBeans(true); //autoStartupOnly = true
	this.running = true;
}

DefaultLifecycleProcessor#startBeans源碼如下:
autoStartupOnly 在onRefresh時(shí)傳入的是true,表示只執(zhí)行可以自動(dòng)啟動(dòng)的bean,即為:SmartLifecycle的實(shí)現(xiàn)類,并且SmartLifecycle#isAutoStartup返回值必須為true。

private void startBeans(boolean autoStartupOnly) {
	Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
	Map<Integer, LifecycleGroup> phases = new TreeMap<>();

	lifecycleBeans.forEach((beanName, bean) -> {
		if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
			int phase = getPhase(bean);
			phases.computeIfAbsent(phase, p -> 
			 new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly)
			).add(beanName, bean);
		}
	});
	if (!phases.isEmpty()) {
		phases.values().forEach(LifecycleGroup::start);
	}
}

而Spring AbstractApplicationContext#doClose退出時(shí),無論是SmartLifecycleLifecycle都會(huì)執(zhí)行isRunning方法,判斷是否已經(jīng)啟動(dòng),返回true表示已經(jīng)啟動(dòng),則執(zhí)行SmartLifecycleLifecyclestop方法。
源碼見:org.springframework.context.support.DefaultLifecycleProcessor#doStop方法。

而執(zhí)行AbstractApplicationContext#doClose一般是應(yīng)用進(jìn)程退出,通過jvm注冊的鉤子方法,或者應(yīng)用程序編碼調(diào)用。
AbstractApplicationContext#registerShutdownHook源碼

@Override
public void registerShutdownHook() {
	if (this.shutdownHook == null) {
		// No shutdown hook registered yet.
		this.shutdownHook = new Thread(SHUTDOWN_HOOK_THREAD_NAME) {
			@Override
			public void run() {
				synchronized (startupShutdownMonitor) {
					doClose();
				}
			}
		};
		Runtime.getRuntime().addShutdownHook(this.shutdownHook);
	}
}

自定義LifecycleProcessor處理Lifecycle

在源碼分析中提到了DefaultLifecycleProcessor,其實(shí)現(xiàn)了LifecycleProcessor接口。然而我們自己也可以實(shí)現(xiàn)該接口,替換默認(rèn)的DefaultLifecycleProcessor。SpringBoot中則是自己配置了DefaultLifecycleProcessor,我們可以按照同樣的方式,覆蓋默認(rèn)的實(shí)現(xiàn)。例如可以讓Lifecycle中的start()方法在onRefresh()時(shí)也能被執(zhí)行。

org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration源碼:

/**
 * {@link EnableAutoConfiguration Auto-configuration} relating to the application
 * context's lifecycle.
 *
 * @author Andy Wilkinson
 * @since 2.3.0
 */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(LifecycleProperties.class)
public class LifecycleAutoConfiguration {

	@Bean(name = AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME)
	@ConditionalOnMissingBean(name = AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME,
			search = SearchStrategy.CURRENT)
	public DefaultLifecycleProcessor defaultLifecycleProcessor(LifecycleProperties properties) {
		DefaultLifecycleProcessor lifecycleProcessor = new DefaultLifecycleProcessor();
		lifecycleProcessor.setTimeoutPerShutdownPhase(properties.getTimeoutPerShutdownPhase().toMillis());
		return lifecycleProcessor;
	}
}

SpringBoot中內(nèi)嵌web容器啟動(dòng)時(shí)機(jī)

SpringBoo中就是通過實(shí)現(xiàn)SmartLifecycle來啟動(dòng)內(nèi)嵌的web容器,實(shí)現(xiàn)類為WebServerStartStopLifecycle

ServletWebServerApplicationContextonRefresh方法中調(diào)用createWebServer,createWebServer方法中創(chuàng)建org.springframework.boot.web.server.WebServer實(shí)例,該對象則包含了控制web容器(tomcat、jetty)的啟動(dòng)與停止方法。

@Override
protected void onRefresh() {
	super.onRefresh();
	try {
		createWebServer();
	}catch (Throwable ex) {
		throw new ApplicationContextException("Unable to start web server", ex);
	}
}

ServletWebServerApplicationContext#createWebServer源碼:

private void createWebServer() {
	WebServer webServer = this.webServer;
	ServletContext servletContext = getServletContext();
	if (webServer == null && servletContext == null) {
		StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");
		ServletWebServerFactory factory = getWebServerFactory();
		createWebServer.tag("factory", factory.getClass().toString());
		this.webServer = factory.getWebServer(getSelfInitializer());
		createWebServer.end();
		getBeanFactory().registerSingleton("webServerGracefulShutdown",
				new WebServerGracefulShutdownLifecycle(this.webServer));
		getBeanFactory().registerSingleton("webServerStartStop",
				new WebServerStartStopLifecycle(this, this.webServer));
	}
	else if (servletContext != null) {
		try {
			getSelfInitializer().onStartup(servletContext);
		}
		catch (ServletException ex) {
			throw new ApplicationContextException("Cannot initialize servlet context", ex);
		}
	}
	initPropertySources();
}

createWebServer方法會(huì)將創(chuàng)建的webServer封裝在WebServerStartStopLifecycle對象中,并注冊到Spring容器中。

org.springframework.boot.web.servlet.context.WebServerStartStopLifecycle源碼如下:

class WebServerStartStopLifecycle implements SmartLifecycle {

	private final ServletWebServerApplicationContext applicationContext;
	private final WebServer webServer;
	private volatile boolean running;

	WebServerStartStopLifecycle(ServletWebServerApplicationContext applicationContext, WebServer webServer) {
		this.applicationContext = applicationContext;
		this.webServer = webServer;
	}

	@Override
	public void start() {
		this.webServer.start();
		this.running = true;
		this.applicationContext
				.publishEvent(new ServletWebServerInitializedEvent(this.webServer, this.applicationContext));
	}

	@Override
	public void stop() { this.webServer.stop(); }

	@Override
	public boolean isRunning() {	return this.running; }

	@Override
	public int getPhase() { return Integer.MAX_VALUE - 1; }
}

WebServerStartStopLifecycle則實(shí)現(xiàn)了SmartLifecycle接口,當(dāng)Spring回調(diào)到SmartLifecycle接口方法時(shí)則調(diào)用this.webServer.start();啟動(dòng)web容器,web容器啟動(dòng)完成之后會(huì)通過applicationContext發(fā)布ServletWebServerInitializedEvent事件,表示web容器啟動(dòng)成功,可以接收http請求。

和SmartInitializingSingleton區(qū)別

相同點(diǎn):SmartInitializingSingletonLifecycleSmartLifecycle都是在所有的單實(shí)例bean創(chuàng)建(getBean方法)之后執(zhí)行。

不同點(diǎn):

  • SmartInitializingSingleton優(yōu)先于Lifecycle、SmartLifecycle執(zhí)行。
  • SmartInitializingSingleton只有一個(gè)afterSingletonsInstantiated方法。而Lifecyclestart,stop,isRunning等方法。
  • 多個(gè)SmartInitializingSingleton實(shí)現(xiàn)之間無法排序控制執(zhí)行的順序,而SmartLifecycle實(shí)現(xiàn)了Phased接口,可以通過int getPhase()控制執(zhí)行循序。
  • SmartInitializingSingleton之間可以通過@DependsOn來控制執(zhí)行順序,但這是由Spring中@DependsOn注解的作用及原理來實(shí)現(xiàn)的. 并不是對SmartInitializingSingleton做了排序。

到此這篇關(guān)于Spring中SmartLifecycle和Lifecycle的作用和區(qū)別的文章就介紹到這了,更多相關(guān)Spring中SmartLifecycle和Lifecycle內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 深入理解java final不可變性

    深入理解java final不可變性

    本文主要介紹了講講java final不可變性,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • 如何通過Java實(shí)現(xiàn)時(shí)間軸過程解析

    如何通過Java實(shí)現(xiàn)時(shí)間軸過程解析

    這篇文章主要介紹了如何通過Java實(shí)現(xiàn)時(shí)間軸過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-02-02
  • Java中判斷對象是否相等的equals()方法使用教程

    Java中判斷對象是否相等的equals()方法使用教程

    與==運(yùn)算符響應(yīng),equals()方法也是Java中對對象進(jìn)行比較的一大方式,要特別注意二者的不同點(diǎn),這個(gè)我們在下文中即將講到,接下來我們就來看一下Java中判斷對象是否相等的equals()方法使用教程
    2016-05-05
  • Java實(shí)現(xiàn)通訊錄管理系統(tǒng)項(xiàng)目

    Java實(shí)現(xiàn)通訊錄管理系統(tǒng)項(xiàng)目

    這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)通訊錄管理系統(tǒng)項(xiàng)目,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • Java高并發(fā)中的交換器Exchanger解析

    Java高并發(fā)中的交換器Exchanger解析

    這篇文章主要介紹了Java高并發(fā)中的交換器Exchanger解析,如果兩個(gè)線程并行處理,但在某個(gè)時(shí)刻需要互相交換自己已經(jīng)處理完的中間數(shù)據(jù),然后才能繼續(xù)往下執(zhí)行,這個(gè)時(shí)候就可以使用 Exchanger,需要的朋友可以參考下
    2023-12-12
  • Java實(shí)現(xiàn)公眾號(hào)功能、關(guān)注及消息推送實(shí)例代碼

    Java實(shí)現(xiàn)公眾號(hào)功能、關(guān)注及消息推送實(shí)例代碼

    公眾號(hào)開發(fā)近些年是一個(gè)比較熱門的方向,下面這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)公眾號(hào)功能、關(guān)注及消息推送的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-11-11
  • Java中6種單例模式寫法代碼實(shí)例

    Java中6種單例模式寫法代碼實(shí)例

    這篇文章主要介紹了Java中6種單例模式寫法代碼實(shí)例,某個(gè)類任何情況下只有一個(gè)實(shí)例,并提供一個(gè)全局訪問點(diǎn)來獲取該實(shí)例,Java6種單例模式有2種懶漢式,2種餓漢式,靜態(tài)內(nèi)部類 ,枚舉類,需要的朋友可以參考下
    2024-01-01
  • 如何使用Java統(tǒng)計(jì)gitlab代碼行數(shù)

    如何使用Java統(tǒng)計(jì)gitlab代碼行數(shù)

    這篇文章主要介紹了如何使用Java統(tǒng)計(jì)gitlab代碼行數(shù),實(shí)現(xiàn)方式通過git腳本將所有的項(xiàng)目拉下來并然后通過進(jìn)行代碼行數(shù)的統(tǒng)計(jì),需要的朋友可以參考下
    2023-10-10
  • java實(shí)現(xiàn)解析二進(jìn)制文件的方法(字符串、圖片)

    java實(shí)現(xiàn)解析二進(jìn)制文件的方法(字符串、圖片)

    本篇文章主要介紹了java實(shí)現(xiàn)解析二進(jìn)制文件的方法(字符串、圖片),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-02-02
  • Springboot啟動(dòng)執(zhí)行特定代碼的方式匯總

    Springboot啟動(dòng)執(zhí)行特定代碼的方式匯總

    這篇文章主要介紹了Springboot啟動(dòng)執(zhí)行特定代碼的幾種方式,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-12-12

最新評(píng)論

宜兰县| 大庆市| 弥渡县| 辉南县| 甘泉县| 芦溪县| 敦煌市| 屯门区| 兴文县| 武定县| 永昌县| 兴义市| 海口市| 广德县| 调兵山市| 万年县| 巨野县| 离岛区| 宁陕县| 丹江口市| 海兴县| 那曲县| 新邵县| 祁连县| 光泽县| 饶阳县| 甘洛县| 正镶白旗| 吉木萨尔县| 蒲城县| 亳州市| 吴旗县| 新竹县| 砚山县| 扶余县| 甘泉县| 肇庆市| 社旗县| 黎城县| 庆元县| 饶河县|