spring - Spring销毁方法顺序
问题描述
假设我们在 Spring 中有以下配置类:
@Configuration
public class MyConfiguration {
@Bean(destroyMethod = "beanDestroyMethod")
public MyBean myBean() {
MyBean myBean = new MyBean();
return myBean;
}
}
以及以下 MyBean 类:
public class MyBean implements DisposableBean {
@PreDestroy
public void preDestroyMethod() {
System.out.println("preDestroyMethod");
}
@Override
public void destroy() throws Exception {
System.out.println("disposableBeanMethod");
}
public void beanDestroyMethod() {
System.out.println("beanDestroyMethod");
}
}
当 bean 被垃圾收集器销毁时,是否保证方法preDestroyMethod、destroy和beanDestroyMethod总是以相同的顺序执行?
如果上一个问题的答案是“是”,那么这 3 种方法的执行顺序是什么?
解决方案
最后我通过使用 AbstractApplicationContext 的 registerShutdownHook() 方法解决了我的问题。
我有以下@Configuration 类:
@Configuration
public class AppConfig {
@Bean(name = "employee1",
initMethod = "beanInitMethod", destroyMethod = "beanDestroyMethod")
public Employee employee1() {
...
}
@Bean(name = "employee2",
initMethod = "beanInitMethod", destroyMethod = "beanDestroyMethod")
public Employee employee2() {
...
}
}
以及以下 bean 类:
public class Employee implements InitializingBean, DisposableBean {
@PostConstruct
public void postConstructMethod() {
System.out.println("1.1 - postConstructMethod");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("1.2 - initializingBeanMethod");
}
public void beanInitMethod() {
System.out.println("1.3 - beanInitMethod");
}
@PreDestroy
public void preDestroyMethod() {
System.out.println("2.1 - preDestroyMethod");
}
@Override
public void destroy() throws Exception {
System.out.println("2.2 - disposableBeanMethod");
}
public void beanDestroyMethod() {
System.out.println("2.3 - beanDestroyMethod");
}
}
以及以下主要课程:
public class AppMain {
public static void main(String[] args) {
AbstractApplicationContext abstractApplicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
abstractApplicationContext.registerShutdownHook();
}
}
输出如下:
1.1 - postConstructMethod
1.2 - initializingBeanMethod
1.3 - beanInitMethod
1.1 - postConstructMethod
1.2 - initializingBeanMethod
1.3 - beanInitMethod
...
2.1 - preDestroyMethod
2.2 - disposableBeanMethod
2.3 - beanDestroyMethod
2.1 - preDestroyMethod
2.2 - disposableBeanMethod
2.3 - beanDestroyMethod
推荐阅读
- android - 带有文件类型的 HTML“输入”标签在移动设备中不起作用。如何解决?
- angular - 从字符串创建一个类
- c# - 如何为日期时间字符串找到正确的自定义格式
- selenium-webdriver - 在使用此类 augmentedDriver 时,它会启动不必要的浏览器实例
- python - 无法在 ubuntu 16.04 的 anaconda 中安装 cv2
- css - 有条件的页面大小
- angular - 如何使用指令检测多个自定义组件的值变化
- javascript - Javascript/Canvas - 为什么我的变量会递增,为什么 if 语句会执行?
- cookies - 如何使用 Katalon Studio 提取浏览器 cookie
- javascript - 如何通过变量将类名传递给jquery函数