Spring 启动 - 不再在配置上调用 destroy()

Spring Boot - No longer calling destroy() on configuration

我有一个使用 Spring Boot 1.1.8 的应用程序,我有一个核心配置 class (Application.groovy),它实现了自定义 destroy() 方法做了一些整理:

@Configuration
@ComponentScan
@EnableAsync(proxyTargetClass=true)
@EnableAutoConfiguration
class Application extends SpringBootServletInitializer {

...

    public void destroy() {
        //do cleanup stuff
    }
}

一切 运行 都很好 - 我看到了以下日志消息(以及许多其他调用销毁消息):

o.s.b.f.support.DisposableBeanAdapter    : Invoking destroy() on bean with name 'application'

我现在已经升级到 Spring Boot 的 1.2.2 并且不再调用 destroy 方法 - 任何人都知道为什么它停止被调用?我仍然在调用 destroy() 方法的日志中看到一些条目,但比以前少了很多。

class 层次结构发生了变化。您的 class 不再(隐含地)继承 DisposableBean (where void destroy() is it's sole function). Make your code implement that interface (and put an @Override on your method for good measure). Or add a @PreDestroy annotation. Details are in the docs

Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface, or the @PreDestroy annotation) can be used.

行为差异的原因相当微妙,这是由于 change in Spring Framework 4.1.3

Spring 框架为每个 @Configuration class 创建了一个 CGLib 代理,这个代理实现了(内部)EnhancedConfiguration 接口。在 4.1.3 之前,此接口同时扩展了 DisposableBeanBeanFactoryAware。在 4.1.3 及更高版本中,它现在仅扩展 BeanFactoryAware。从 Spring 容器的角度来看,这意味着您的应用程序 class 正在实施 DisposableBean 但现在不再实施了。

与其依赖框架的实现细节,不如明确说明需要调用 destroy()。您可以实现 DisposableBean 或使用 @PreDestroy.

注释您的方法