![ace6d50904327145f579f97c0acc8b1c.png](https://img-blog.csdnimg.cn/img_convert/ace6d50904327145f579f97c0acc8b1c.png)
销毁回调
Spring的初始化回调你真的搞懂了吗?
接着前篇,有初始化对应着就有销毁。Spring提供了多种方式的销毁回调方法,这些方法在手动关闭容器的时候就会触发。
销毁回调方式:
- 后置处理器DestructionAwareBeanPostProcessor的postProcessBeforeDestruction()方法,此方式是对所有bean有效
- 在类方法上使用@PreDestroy注解
- 实现接口DisposableBean的destory()方法
- 自定义回调方法,@Bean(destroyMethod = "beanDestoryCallbackMethod")
- 实现AutoCloseable接口或者Closeable接口的bean(当且仅当此bean没有任何自定义销毁回调,也就是说此bean没有使用前面的2,3,4这三种方式)
仍然按照前篇的思路,先演示,再提疑问,再读源码。
演示案例
自定义一个实现前面四种方式中的后三种方式的bean,实现DisposableBean接口,在bean中使用@PreDestory注解。然后在注入容器的时候使用@Bean注解。
package com.ubuntuvim.spring.createbean;import org.springframework.beans.factory.DisposableBean;import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;import org.springframework.context.support.AbstractApplicationContext;import javax.annotation.PreDestroy;import java.io.IOException;/** * 和InitCallbackBean是相互呼应的,有销毁回调对应着就有销毁的回调。 * 验证各种销毁回调方法的执行顺序: * 1. 执行销毁回调DestructionAwareBeanPostProcessor.postProcessBeforeDestruction()方法 * 2. 执行销毁回调@PreDestroy注解的回调方法twoDestroy() * 3. 执行销毁回调@PreDestroy注解的回调方法oneDestroy() * 4. 执行销毁回调DisposableBean.destory()方法 * 5. 执行销毁回调@Bean(destroyMethod = "beanDestoryCallbackMethod")的方法 * * 需要注意的是,这些销毁的回调方法需要手动调用容器的关闭方法才会触发。触发方法如下: * @see AbstractApplicationContext#close() * 最终会调用到这个类的方法处理上述回调接口。 * @see DisposableBeanAdapter#destroy() * * @Author: ubuntuvim * @Date: 2020/10/18 下午5:17 */public class DestoryCallbackBean implements DisposableBean, /*Closeable, */AutoCloseable { // 实现DisposableBean接口的方法 @Override public void destroy() throws Exception { System.out.println("执行销毁回调DisposableBean.destory()方法"); } // 自定义销毁方法:@Bean(destroyMethod = "beanDestoryCallbackMethod") private void beanDestoryCallbackMethod() { System.out.println("执行销毁回调@Bean(destroyMethod = "beanDestoryCallbackMethod")的方法"); } // 如果有一个同名销毁方法会不会被读取使用??不会,因为@Bean只支持无参方法 private void beanDestoryCallbackMethod(Fruit apple) { apple.eatable(); System.out.println("执行销毁回调@Bean(dest