spring的生命周期方法给用户提供了多种扩展方式
构建Bean时:
- 使用@PostConstruct
- 实现InitializingBean接口的afterPropertiesSet方法
- 自定义init-method(并在@Bean中或者xml中配置init-method)
销毁Bean时:
- @PreDestroy
- destroy-method
- DisposableBean -- destroy
构建Bean三者的执行顺序示例:
public class Pig implements InitializingBean {
@PostConstruct
public void postConst() {
System.out.println("@PostConstruct...");
}
public void initMethod() {
System.out.println("initMethod...");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean--afterPropertiesSet...");
}
}
测试:
public class BeanInitMethodDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ConfigurableListableBeanFactory beanFactory = ctx.getBeanFactory();
ctx.register(BeanInitMethodDemo.class);
ctx.refresh();
ctx.close();
}
@Bean(initMethod = "initMethod")
public Pig pig() {
return new Pig();
}
}
输出:
@PostConstruct...
InitializingBean--afterPropertiesSet...
initMethod...
可见执行顺序为:@PostConstruct --> InitializingBean --> 自定义init-method
销毁Bean执行顺序
示例代码:
public class Pig implements DisposableBean {
@PreDestroy
public void preDestroy() {
System.out.println("@PreDestroy...");
}
@PreDestroy
public void destroyMethod() {
System.out.println("自定义destroyMethod...");
}
@Override
public void destroy() throws Exception {
System.out.println("DisposableBean--destroy()");
}
}
测试:
public class BeanDestroyMethodDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(BeanDestroyMethodDemo.class);
ctx.refresh();
Object pig = ctx.getBean("pig");
System.out.println(pig);
ctx.close();
}
@Bean(destroyMethod = "destroyMethod")
public Pig pig() {
return new Pig();
}
}
输出:
com.demo.beans.definition.pojo.Pig@7a187f14
@PreDestroy...
自定义destroyMethod...
DisposableBean--destroy()
可见:执行顺序为
@PreDestroy --> 自定义destroyMethod --> DisposableBean--destroy()方法