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

兩種Spring服務(wù)關(guān)閉時(shí)對(duì)象銷毀的實(shí)現(xiàn)方法

 更新時(shí)間:2023年04月28日 14:54:03   作者:祁山墨子  
spring提供了兩種方式用于實(shí)現(xiàn)對(duì)象銷毀時(shí)去執(zhí)行的操作,本文主要為大家詳細(xì)介紹了這兩種方式的具體實(shí)現(xiàn),文中的示例代碼講解詳細(xì),希望對(duì)大家有所幫助

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)文章

最新評(píng)論

娄底市| 凤翔县| 策勒县| 夏河县| 巫溪县| 沁源县| 武清区| 仁布县| 香港| 安岳县| 定南县| 美姑县| 富民县| 弥勒县| 绥宁县| 嘉义市| 平阴县| 阿荣旗| 朝阳区| 平谷区| 织金县| 安泽县| 迁西县| 左权县| 扶风县| 衡阳市| 双鸭山市| 临湘市| 贡嘎县| 南宫市| 荆门市| 太和县| 炉霍县| 富蕴县| 舞阳县| 定日县| 含山县| 若尔盖县| 司法| 南丰县| 囊谦县|