经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
如何实现Spring中服务关闭时对象销毁执行代码
来源:cnblogs  作者:祁山墨子  时间:2023/4/28 12:10:55  对本文有异议

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

1.实现DisposableBean接口的destroy

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

3.实现SmartLifecycle接口的stop方法

  1. package com.wyf.service;
  2. import org.springframework.beans.factory.DisposableBean;
  3. import org.springframework.context.Lifecycle;
  4. import org.springframework.context.SmartLifecycle;
  5. import org.springframework.context.annotation.ComponentScan;
  6. import org.springframework.stereotype.Component;
  7. import javax.annotation.PreDestroy;
  8. @Component
  9. public class UserService implements DisposableBean, SmartLifecycle {
  10. boolean isRunning = false;
  11. @Override
  12. public void destroy() throws Exception {
  13. System.out.println(this.getClass().getSimpleName()+" is destroying.....");
  14. }
  15. @PreDestroy
  16. public void preDestory(){
  17. System.out.println(this.getClass().getSimpleName()+" is pre destory....");
  18. }
  19. @Override
  20. public void start() {
  21. System.out.println(this.getClass().getSimpleName()+" is start..");
  22. isRunning=true;
  23. }
  24. @Override
  25. public void stop() {
  26. System.out.println(this.getClass().getSimpleName()+" is stop...");
  27. isRunning=false;
  28. }
  29. @Override
  30. public boolean isRunning() {
  31. return isRunning;
  32. }
  33. }

那么这个时候我们去启动一个spring容器

  1. package com.wyf;
  2. import org.springframework.context.support.ClassPathXmlApplicationContext;
  3. public class Application {
  4. public static void main(String[] args) {
  5. ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  6. }
  7. }

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

  1. package com.wyf;
  2. import org.springframework.context.support.ClassPathXmlApplicationContext;
  3. public class Application {
  4. public static void main(String[] args) {
  5. ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  6. //添加一个关闭钩子,用于触发对象销毁操作
  7. context.registerShutdownHook();
  8. context.close();
  9. }
  10. }

实际上我们去查看源码会发现本质上这两种方式都是去调用了同一个方法org.springframework.context.support.AbstractApplicationContext#doClose

  1. @Override
  2. public void registerShutdownHook() {
  3. if (this.shutdownHook == null) {
  4. // No shutdown hook registered yet.
  5. this.shutdownHook = new Thread(SHUTDOWN_HOOK_THREAD_NAME) {
  6. @Override
  7. public void run() {
  8. synchronized (startupShutdownMonitor) {
  9. doClose();
  10. }
  11. }
  12. };
  13. Runtime.getRuntime().addShutdownHook(this.shutdownHook);
  14. }
  15. }

registerShutdownHook方法其实是创建了一个jvm shutdownhook(关闭钩子),这个钩子本质上是一个线程,他会在jvm关闭的时候启动并执行线程实现的方法。而spring的关闭钩子实现则是执行了org.springframework.context.support.AbstractApplicationContext#doClose这个方法去执行一些spring的销毁方法

  1. @Override
  2. public void close() {
  3. synchronized (this.startupShutdownMonitor) {
  4. doClose();
  5. // If we registered a JVM shutdown hook, we don't need it anymore now:
  6. // We've already explicitly closed the context.
  7. if (this.shutdownHook != null) {
  8. try {
  9. Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
  10. }
  11. catch (IllegalStateException ex) {
  12. // ignore - VM is already shutting down
  13. }
  14. }
  15. }
  16. }

而close方法则是执行直接执行了doClose方法,并且在执行之后会判断是否注册了关闭钩子,如果注册了则注销掉这个钩子,因为已经执行过doClose了,不应该再执行一次

  1. @Override
  2. public void close() {
  3. synchronized (this.startupShutdownMonitor) {
  4. doClose();
  5. // If we registered a JVM shutdown hook, we don't need it anymore now:
  6. // We've already explicitly closed the context.
  7. if (this.shutdownHook != null) {
  8. try {
  9. Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
  10. }
  11. catch (IllegalStateException ex) {
  12. // ignore - VM is already shutting down
  13. }
  14. }
  15. }
  16. }

doClose方法源码分析

  1. @SuppressWarnings("deprecation")
  2. protected void doClose() {
  3. // Check whether an actual close attempt is necessary...
  4. //判断是否有必要执行关闭操作
  5. //如果容器正在执行中,并且以CAS的方式设置关闭标识成功,则执行后续关闭操作,当然这个标识仅仅是标识,并没有真正修改容器的状态
  6. if (this.active.get() && this.closed.compareAndSet(false, true)) {
  7. if (logger.isDebugEnabled()) {
  8. logger.debug("Closing " + this);
  9. }
  10. if (!NativeDetector.inNativeImage()) {
  11. LiveBeansView.unregisterApplicationContext(this);
  12. }
  13. try {
  14. // Publish shutdown event.
  15. //发布容器关闭事件,通知所有监听器
  16. publishEvent(new ContextClosedEvent(this));
  17. }
  18. catch (Throwable ex) {
  19. logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);
  20. }
  21. // Stop all Lifecycle beans, to avoid delays during individual destruction.
  22. //如果存在bean实现的Lifecycle接口,则执行onClose(),lifecycleProcessor会对所有Lifecycle进行分组然后分批执行stop方法
  23. if (this.lifecycleProcessor != null) {
  24. try {
  25. this.lifecycleProcessor.onClose();
  26. }
  27. catch (Throwable ex) {
  28. logger.warn("Exception thrown from LifecycleProcessor on context close", ex);
  29. }
  30. }
  31. // Destroy all cached singletons in the context's BeanFactory.
  32. //销毁所有缓存的单例bean
  33. destroyBeans();
  34. // Close the state of this context itself.
  35. //关闭bean工厂
  36. closeBeanFactory();
  37. // Let subclasses do some final clean-up if they wish...
  38. //为子类预留的方法允许子类去自定义一些销毁操作
  39. onClose();
  40. // Reset local application listeners to pre-refresh state.
  41. //将本地应用程序侦听器重置为预刷新状态。
  42. if (this.earlyApplicationListeners != null) {
  43. this.applicationListeners.clear();
  44. this.applicationListeners.addAll(this.earlyApplicationListeners);
  45. }
  46. // Switch to inactive.
  47. //设置上下文到状态为关闭状态
  48. this.active.set(false);
  49. }
  50. }
  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只不过是把这些能力集成在一个接口里面方便管理和使用。

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

原文链接:https://www.cnblogs.com/qishanmozi/p/17361767.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号