一、初始化执行顺序
1、基础准备
- ① 编写Bean1
public class Bean1 implements InitializingBean {
private static final Logger log = LoggerFactory.getLogger(Bean1.class);
@PostConstruct
public void init1(){
log.debug("初始化1 @PostConstruct");
}
@Override
public void afterPropertiesSet() throws Exception {
log.debug("初始化2 afterPropertiesSet");
}
public void init3(){
log.debug("初始化3 @Bean(initMethod = \"\")");
}
}
- ② 编写启动类
@SpringBootApplication
public class Demo07 {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Demo07.class, args);
context.close();
}
@Bean(initMethod = "init3")
public Bean1 bean1(){return new Bean1();}
}
- ③ 测试

2、总结
@PostConstruct → InitializingBean#afterPropertiesSet → @Bean(initMethod = "")
二、销毁执行顺序
1、基础准备
- ① 编写Bean2
public class Bean2 implements DisposableBean {
private static final Logger log = LoggerFactory.getLogger(Bean2.class);
@PreDestroy
public void destroy1(){
log.debug("销毁方法1 @PreDestroy");
}
@Override
public void destroy() throws Exception {
log.debug("销毁方法2 destroy");
}
public void destroy3(){
log.debug("销毁方法3 @Bean(\"\")");
}
}
- ② 修改启动类
添加如下内容:
@Bean(destroyMethod = "destroy3")
public Bean2 bean2(){return new Bean2();}
- ③ 测试

2、总结
@PreDestroy → DisposableBean#destroy → @Bean(destroyMethod = "")
三、结尾
以上即为初始化与销毁执行顺序的全部内容,感谢阅读。
网友评论