内容概要:
- Spring 提供了多种初始化和销毁手段
- 它们的执行顺序
afterPropertiesSet()
方法initMethod
属性,标注Bean初始化方法destroy()
方法destroyMethod
属性,标注Bean初始化方法@SpringBootApplication
public class BeanInitAndDestroy {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(BeanInitAndDestroy.class, args);
// 销毁容器
context.close();
}
@Bean(initMethod = "init3")
public Bean1 bean1() {
return new Bean1();
}
@Bean(destroyMethod = "destroy3")
public Bean2 bean2() {
return new Bean2();
}
@Slf4j
static class Bean1 implements InitializingBean {
@PostConstruct
public void init1() {
log.debug("初始化1");
}
@Override
public void afterPropertiesSet() throws Exception {
log.debug("初始化2");
}
public void init3() {
log.debug("初始化3");
}
}
@Slf4j
static class Bean2 implements DisposableBean {
@PreDestroy
public void destory1() {
log.debug("销毁1");
}
@Override
public void destroy() throws Exception {
log.debug("销毁2");
}
public void destroy3() {
log.debug("销毁3");
}
}
}
输出
BeanInitAndDestroy$Bean1 : 初始化1
BeanInitAndDestroy$Bean1 : 初始化2
BeanInitAndDestroy$Bean1 : 初始化3
BeanInitAndDestroy$Bean2 : 销毁1
BeanInitAndDestroy$Bean2 : 销毁2
BeanInitAndDestroy$Bean2 : 销毁3