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。所以这取决于你想要做什么。按照文档

  1. 使用的ContextLoaderListener contextDestroyed(ServletContextEvent事件): 关闭根web应用上下文。 docs
  2. 使用DisposableBean销毁方法: 由BeanFactory在销毁单例时调用。如果您不想实现弹簧专用接口,则可以查看@PreDestroy注释。