DisposableBean.destroy()与ContextLoaderListener.contextDestroyed
问题描述:
在我的一个服务类中,我使用了Executors.newFixedThreadPool(size)
作为ExecutorService。我在我的应用程序中通过使用bean,然后最后我通过扩展ContextLoaderListener类并从其contextDestroyed(ServletContextEvent servletContextEvent)
方法DisposableBean.destroy()与ContextLoaderListener.contextDestroyed
中调用服务类的销毁方法来关闭FixedThreadPool,但我也可以直接从服务关闭ExecutorService通过实现DisposableBean
接口并在其destroy()方法中调用shutDown来实现。
所以在上述两种方法中会有什么区别,哪一种更适合用于正常关闭/重新部署web-app。
答
您绝对应该使用DisposableBean
(或者您可以指定一个自定义的销毁方法,这些方法之间没有区别)。
第一个原因是这样做更合乎逻辑,因为这是Bean
而不是Context
的责任。第二个也是更重要的原因是,使用contextDestroyed
方法时,您可能会使Service
无法使用,而其他Beans
仍在使用它。
答
最根本的区别是DisposableBean是针对特定的bean,而使用ContextLoaderListener则针对整个WebApplicationContext。所以这取决于你想要做什么。按照文档
- 使用的ContextLoaderListener contextDestroyed(ServletContextEvent事件): 关闭根web应用上下文。 docs
- 使用DisposableBean销毁方法: 由BeanFactory在销毁单例时调用。如果您不想实现弹簧专用接口,则可以查看@PreDestroy注释。