如何实现Spring中服务关闭时对象销毁执行代码

博客 动态
0 147
羽尘
羽尘 2023-04-28 12:54:34
悬赏:0 积分 收藏

如何实现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);
        }
    }
  1. 首先判断当前容器是否正在运行中,然后尝试通过CAS的方式设置关闭标识为true,这相当于一个锁,避免其他线程再去执行关闭操作。
  2. 发布容器关闭事件,通知所有监听器,监听器收到事件后执行其实现的监听方法
  3. 如果存在bean实现的Lifecycle接口,并且正在运行中,则执行Lifecycle.stop()方法,需要注意的是如果是实现Lifecycle,那么start方法需要使用context.start()去显示调用才会执行,而实现SmartLifecycle则会自动执行,而stop方法是否执行依赖于isRunning()方法的返回,如果为true那么无论是用哪一种Lifecycle实现,则都会执行stop,当然,你也可以实现isRunning方法让他默认返回true,那么你也就无需去关注start了。
  4. 销毁所有的单例bean,这里会去执行实现了org.springframework.beans.factory.DisposableBean#destroy方法的bean的destroy方法,以及其带有@PreDestroy注解的方法。
  5. 关闭Bean工厂,这一步很简单,就是设置当前上下文持有的bean工厂引用为null即可
  6. 执行onClose()方法,这里是为子类预留的扩展,不同的ApplicationContext有不同的实现方式,但是本文主讲的不是这个就不谈了
  7. 将本地应用程序侦听器重置为预刷新状态。
  8. 将ApplicationContext的状态设置为关闭状态,容器正式关闭完成。

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

本文只是简单看了一下源码,很多细节没有深究,必然会有不少错误的地方但是总体逻辑是没问题的,如果您觉得有些地方不对,欢迎指教。

posted @ 2023-04-28 12:08  祁山墨子  阅读(3)  评论(1编辑  收藏  举报
回帖
    羽尘

    羽尘 (王者 段位)

    2233 积分 (2)粉丝 (11)源码

     

    温馨提示

    亦奇源码

    最新会员