java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring对象销毁

两种Spring服务关闭时对象销毁的实现方法

作者:祁山墨子

spring提供了两种方式用于实现对象销毁时去执行的操作,本文主要为大家详细介绍了这两种方式的具体实现,文中的示例代码讲解详细,希望对大家有所帮助

spring提供了两种方式用于实现对象销毁时去执行操作

1.实现DisposableBean接口的destroy

2.在bean类的方法上增加@PreDestroy方法,那么这个方法会在DisposableBean.destory方法前触发

3.实现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;
        }

}

那么这个时候我们去启动一个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");

    }
}

这个时候其实销毁方法是不会执行的,我们可以通过,调用close方法触发或者调用registerShutdownHook注册一个钩子来在容器关闭时触发销毁方法

package com.wyf;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Application {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        //添加一个关闭钩子,用于触发对象销毁操作
        context.registerShutdownHook();

        context.close();
    }
}

实际上我们去查看源码会发现本质上这两种方式都是去调用了同一个方法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方法其实是创建了一个jvm shutdownhook(关闭钩子),这个钩子本质上是一个线程,他会在jvm关闭的时候启动并执行线程实现的方法。而spring的关闭钩子实现则是执行了org.springframework.context.support.AbstractApplicationContext#doClose这个方法去执行一些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方法则是执行直接执行了doClose方法,并且在执行之后会判断是否注册了关闭钩子,如果注册了则注销掉这个钩子,因为已经执行过doClose了,不应该再执行一次

    @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...
        //判断是否有必要执行关闭操作
        //如果容器正在执行中,并且以CAS的方式设置关闭标识成功,则执行后续关闭操作,当然这个标识仅仅是标识,并没有真正修改容器的状态
        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.
                //发布容器关闭事件,通知所有监听器
                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实现的Lifecycle接口,则执行onClose(),lifecycleProcessor会对所有Lifecycle进行分组然后分批执行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.
            //关闭bean工厂
            closeBeanFactory();

            // Let subclasses do some final clean-up if they wish...
            //为子类预留的方法允许子类去自定义一些销毁操作
            onClose();

            // Reset local application listeners to pre-refresh state.
            //将本地应用程序侦听器重置为预刷新状态。
            if (this.earlyApplicationListeners != null) {
                this.applicationListeners.clear();
                this.applicationListeners.addAll(this.earlyApplicationListeners);
            }

            // Switch to inactive.
            //设置上下文到状态为关闭状态
            this.active.set(false);
        }
    }

tips:其实Lifecycle不算是bean销毁时的操作,而是bean销毁前操作,这个是bean生命周期管理实现的接口,相当于spring除了自己去对bean的生命周期管理之外,还允许你通过这个接口来在bean的不同生命周期阶段去执行各种逻辑,我个人理解和另外两种方法的本质上是差不多的,只是谁先执行谁后执行的问题,Lifecycle只不过是把这些能力集成在一个接口里面方便管理和使用。

到此这篇关于两种Spring服务关闭时对象销毁的实现方法的文章就介绍到这了,更多相关Spring对象销毁内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文