XML配置中, bean 标签, init-method 用来指定bean初始化后调用的方法, destroy-method 用来指定bean销毁前调用的方法。如果想统一设置,可以在 beans 中设置 default-init-method 属性。
注解中, @Bean 注解,initMethod用来指定bean初始化后调用的方法, destroyMethod 用来指定bean销毁前调用的方法。
org.springframework.beans.factory.InitializingBean接口,在其他初始化工作完成后,才开始调用他的 afterPropertiesSet() 方法.
org.springframework.beans.factory.DisposableBean接口,在容器销毁时,会调用 destroy() 这个方法。
@PostConstruct和@PreDestroy不属于spring,而是属于JSR-250规则,日常用的较多的,还是这两个注解。
当这三种生命周期机制同时作用于同一个bean时,执行顺序如下:
初始化:@PostConstruct > InitializingBean的afterPropertiesSet()方法 > init()方法。
销毁:@PreDestroy > DisposableBean的destroy()方法 > destroy()方法。
MyBean
public class MyBean implements InitializingBean, DisposableBean {
private String name;
public MyBean(String name) {
System.out.println("name:" + name);
this.name = name;
}
public void initMethod() {
System.out.println("initMethod");
}
public void destroyMethod() {
System.out.println("destroyMethod");
}
@PostConstruct
public void postConstruct() {
System.out.println("postConstruct");
}
@PreDestroy
public void preDestroy() {
System.out.println("preDestroy");
}
@Override
public void destroy() throws Exception {
System.out.println("destroy");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet");
}
}
MyConfig
@Configuration
public class MyConfig {
@Bean(initMethod = "initMethod", destroyMethod = "destroyMethod")
public MyBean myBean() {
return new MyBean("张三");
}
}
测试代码
@Test
public void test() {
ApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class);
System.out.println("开始销毁");
((AnnotationConfigApplicationContext) app).close();
}
运行结果如下
XML的配置同@bean注解,这边不做演示。