有时,我们需要在关闭 Spring 容器之前做一些额外的工作,例如关闭资源文件。
这时,我们可以实现 DisposableBean 接口并覆盖其 destroy 方法:

@Service
public class DService implements InitializingBean, DisposableBean {
    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean destroy");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean afterPropertiesSet");
    }
}

这样,在 Spring 容器销毁之前会调用 destroy 方法。
通常,我们会同时实现 InitializingBean 和 DisposableBean 接口,并覆盖初始化方法和销毁方法。

最后修改:2025 年 08 月 14 日
个人博客