兩種Spring服務(wù)關(guān)閉時(shí)對(duì)象銷毀的實(shí)現(xiàn)方法
spring提供了兩種方式用于實(shí)現(xiàn)對(duì)象銷毀時(shí)去執(zhí)行操作
1.實(shí)現(xiàn)DisposableBean接口的destroy
2.在bean類的方法上增加@PreDestroy方法,那么這個(gè)方法會(huì)在DisposableBean.destory方法前觸發(fā)
3.實(shí)現(xiàn)SmartLifecycle接口的stop方法
package com.wyf.service;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.Lifecycle;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
@Component
public class UserService implements DisposableBean, SmartLifecycle {
boolean isRunning = false;
@Override
public void destroy() throws Exception {
System.out.println(this.getClass().getSimpleName()+" is destroying.....");
}
@PreDestroy
public void preDestory(){
System.out.println(this.getClass().getSimpleName()+" is pre destory....");
}
@Override
public void start() {
System.out.println(this.getClass().getSimpleName()+" is start..");
isRunning=true;
}
@Override
public void stop() {
System.out.println(this.getClass().getSimpleName()+" is stop...");
isRunning=false;
}
@Override
public boolean isRunning() {
return isRunning;
}
}那么這個(gè)時(shí)候我們?nèi)?dòng)一個(gè)spring容器
package com.wyf;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
}
}
這個(gè)時(shí)候其實(shí)銷毀方法是不會(huì)執(zhí)行的,我們可以通過(guò),調(diào)用close方法觸發(fā)或者調(diào)用registerShutdownHook注冊(cè)一個(gè)鉤子來(lái)在容器關(guān)閉時(shí)觸發(fā)銷毀方法
package com.wyf;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
//添加一個(gè)關(guān)閉鉤子,用于觸發(fā)對(duì)象銷毀操作
context.registerShutdownHook();
context.close();
}
}
實(shí)際上我們?nèi)ゲ榭丛创a會(huì)發(fā)現(xiàn)本質(zhì)上這兩種方式都是去調(diào)用了同一個(gè)方法org.springframework.context.support.AbstractApplicationContext#doClose
@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);
}
}registerShutdownHook方法其實(shí)是創(chuàng)建了一個(gè)jvm shutdownhook(關(guān)閉鉤子),這個(gè)鉤子本質(zhì)上是一個(gè)線程,他會(huì)在jvm關(guān)閉的時(shí)候啟動(dòng)并執(zhí)行線程實(shí)現(xiàn)的方法。而spring的關(guān)閉鉤子實(shí)現(xiàn)則是執(zhí)行了org.springframework.context.support.AbstractApplicationContext#doClose這個(gè)方法去執(zhí)行一些spring的銷毀方法
@Override
public void close() {
synchronized (this.startupShutdownMonitor) {
doClose();
// If we registered a JVM shutdown hook, we don't need it anymore now:
// We've already explicitly closed the context.
if (this.shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
}
catch (IllegalStateException ex) {
// ignore - VM is already shutting down
}
}
}
}而close方法則是執(zhí)行直接執(zhí)行了doClose方法,并且在執(zhí)行之后會(huì)判斷是否注冊(cè)了關(guān)閉鉤子,如果注冊(cè)了則注銷掉這個(gè)鉤子,因?yàn)橐呀?jīng)執(zhí)行過(guò)doClose了,不應(yīng)該再執(zhí)行一次
@Override
public void close() {
synchronized (this.startupShutdownMonitor) {
doClose();
// If we registered a JVM shutdown hook, we don't need it anymore now:
// We've already explicitly closed the context.
if (this.shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
}
catch (IllegalStateException ex) {
// ignore - VM is already shutting down
}
}
}
}doClose方法源碼分析
@SuppressWarnings("deprecation")
protected void doClose() {
// Check whether an actual close attempt is necessary...
//判斷是否有必要執(zhí)行關(guān)閉操作
//如果容器正在執(zhí)行中,并且以CAS的方式設(shè)置關(guān)閉標(biāo)識(shí)成功,則執(zhí)行后續(xù)關(guān)閉操作,當(dāng)然這個(gè)標(biāo)識(shí)僅僅是標(biāo)識(shí),并沒有真正修改容器的狀態(tài)
if (this.active.get() && this.closed.compareAndSet(false, true)) {
if (logger.isDebugEnabled()) {
logger.debug("Closing " + this);
}
if (!NativeDetector.inNativeImage()) {
LiveBeansView.unregisterApplicationContext(this);
}
try {
// Publish shutdown event.
//發(fā)布容器關(guān)閉事件,通知所有監(jiān)聽器
publishEvent(new ContextClosedEvent(this));
}
catch (Throwable ex) {
logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);
}
// Stop all Lifecycle beans, to avoid delays during individual destruction.
//如果存在bean實(shí)現(xiàn)的Lifecycle接口,則執(zhí)行onClose(),lifecycleProcessor會(huì)對(duì)所有Lifecycle進(jìn)行分組然后分批執(zhí)行stop方法
if (this.lifecycleProcessor != null) {
try {
this.lifecycleProcessor.onClose();
}
catch (Throwable ex) {
logger.warn("Exception thrown from LifecycleProcessor on context close", ex);
}
}
// Destroy all cached singletons in the context's BeanFactory.
//銷毀所有緩存的單例bean
destroyBeans();
// Close the state of this context itself.
//關(guān)閉bean工廠
closeBeanFactory();
// Let subclasses do some final clean-up if they wish...
//為子類預(yù)留的方法允許子類去自定義一些銷毀操作
onClose();
// Reset local application listeners to pre-refresh state.
//將本地應(yīng)用程序偵聽器重置為預(yù)刷新狀態(tài)。
if (this.earlyApplicationListeners != null) {
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Switch to inactive.
//設(shè)置上下文到狀態(tài)為關(guān)閉狀態(tài)
this.active.set(false);
}
}
- 首先判斷當(dāng)前容器是否正在運(yùn)行中,然后嘗試通過(guò)CAS的方式設(shè)置關(guān)閉標(biāo)識(shí)為true,這相當(dāng)于一個(gè)鎖,避免其他線程再去執(zhí)行關(guān)閉操作。
- 發(fā)布容器關(guān)閉事件,通知所有監(jiān)聽器,監(jiān)聽器收到事件后執(zhí)行其實(shí)現(xiàn)的監(jiān)聽方法
- 如果存在bean實(shí)現(xiàn)的Lifecycle接口,并且正在運(yùn)行中,則執(zhí)行Lifecycle.stop()方法,需要注意的是如果是實(shí)現(xiàn)Lifecycle,那么start方法需要使用context.start()去顯示調(diào)用才會(huì)執(zhí)行,而實(shí)現(xiàn)SmartLifecycle則會(huì)自動(dòng)執(zhí)行,而stop方法是否執(zhí)行依賴于isRunning()方法的返回,如果為true那么無(wú)論是用哪一種Lifecycle實(shí)現(xiàn),則都會(huì)執(zhí)行stop,當(dāng)然,你也可以實(shí)現(xiàn)isRunning方法讓他默認(rèn)返回true,那么你也就無(wú)需去關(guān)注start了。
- 銷毀所有的單例bean,這里會(huì)去執(zhí)行實(shí)現(xiàn)了
org.springframework.beans.factory.DisposableBean#destroy方法的bean的destroy方法,以及其帶有@PreDestroy注解的方法。 - 關(guān)閉Bean工廠,這一步很簡(jiǎn)單,就是設(shè)置當(dāng)前上下文持有的bean工廠引用為null即可
- 執(zhí)行onClose()方法,這里是為子類預(yù)留的擴(kuò)展,不同的ApplicationContext有不同的實(shí)現(xiàn)方式,但是本文主講的不是這個(gè)就不談了
- 將本地應(yīng)用程序偵聽器重置為預(yù)刷新狀態(tài)。
- 將ApplicationContext的狀態(tài)設(shè)置為關(guān)閉狀態(tài),容器正式關(guān)閉完成。
tips:其實(shí)Lifecycle不算是bean銷毀時(shí)的操作,而是bean銷毀前操作,這個(gè)是bean生命周期管理實(shí)現(xiàn)的接口,相當(dāng)于spring除了自己去對(duì)bean的生命周期管理之外,還允許你通過(guò)這個(gè)接口來(lái)在bean的不同生命周期階段去執(zhí)行各種邏輯,我個(gè)人理解和另外兩種方法的本質(zhì)上是差不多的,只是誰(shuí)先執(zhí)行誰(shuí)后執(zhí)行的問題,Lifecycle只不過(guò)是把這些能力集成在一個(gè)接口里面方便管理和使用。
到此這篇關(guān)于兩種Spring服務(wù)關(guān)閉時(shí)對(duì)象銷毀的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)Spring對(duì)象銷毀內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入解析Java設(shè)計(jì)模式編程中觀察者模式的運(yùn)用
這篇文章主要介紹了Java設(shè)計(jì)模式編程中觀察者模式的運(yùn)用,觀察者模式主要是為了將對(duì)象進(jìn)行與被觀察者一樣的實(shí)現(xiàn),需要的朋友可以參考下2016-02-02
一文帶你徹底了解Java8中的Lambda,函數(shù)式接口和Stream
這篇文章主要為大家詳細(xì)介紹了解Java8中的Lambda,函數(shù)式接口和Stream的用法和原理,文中的示例代碼簡(jiǎn)潔易懂,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-08-08
根據(jù)list中對(duì)象的屬性去重和排序小結(jié)(必看篇)
下面小編就為大家?guī)?lái)一篇根據(jù)list中對(duì)象的屬性去重和排序小結(jié)(必看篇)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05
java中servlet實(shí)現(xiàn)登錄驗(yàn)證的方法
做web開發(fā),登錄驗(yàn)證是免不了的,今天學(xué)習(xí)了servlet的登錄驗(yàn)證,當(dāng)然是很簡(jiǎn)單的,沒有使用session,request等作用域?qū)ο?,所以還是可以直接通過(guò)地址訪問網(wǎng)頁(yè)的。2013-05-05
創(chuàng)建動(dòng)態(tài)代理對(duì)象bean,并動(dòng)態(tài)注入到spring容器中的操作
這篇文章主要介紹了創(chuàng)建動(dòng)態(tài)代理對(duì)象bean,并動(dòng)態(tài)注入到spring容器中的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02
Rabbitmq延遲隊(duì)列實(shí)現(xiàn)定時(shí)任務(wù)的方法
這篇文章主要介紹了Rabbitmq延遲隊(duì)列實(shí)現(xiàn)定時(shí)任務(wù),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
Spring Boot中定時(shí)任務(wù)Cron表達(dá)式的終極指南最佳實(shí)踐記錄
本文詳細(xì)介紹了SpringBoot中定時(shí)任務(wù)的實(shí)現(xiàn)方法,特別是Cron表達(dá)式的使用技巧和高級(jí)用法,從基礎(chǔ)語(yǔ)法到復(fù)雜場(chǎng)景,從快速啟用到調(diào)試驗(yàn)證,再到常見問題的解決,涵蓋了定時(shí)任務(wù)開發(fā)的全過(guò)程,感興趣的朋友一起看看吧2025-03-03
Java Web實(shí)現(xiàn)session過(guò)期后自動(dòng)跳轉(zhuǎn)到登陸頁(yè)功能【基于過(guò)濾器】
這篇文章主要介紹了Java Web實(shí)現(xiàn)session過(guò)期后自動(dòng)跳轉(zhuǎn)到登陸頁(yè)功能,涉及java過(guò)濾器針對(duì)session的判斷與跳轉(zhuǎn)相關(guān)操作技巧,需要的朋友可以參考下2017-11-11
macOS上使用gperftools定位Java內(nèi)存泄漏問題及解決方案
這篇文章主要介紹了macOS上使用gperftools定位Java內(nèi)存泄漏問題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07

