假设我们在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种方法的执行顺序是什么?
答案 0 :(得分:0)
最后,我通过使用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