Spring初始化与销毁顺序案例演示详解
作者:tanglin_030907031026 时间:2021-06-08 14:33:10
演示 - 初始化销毁顺序
/*
初始化和销毁的执行顺序
*/
@SpringBootApplication
public class A07_1 {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(A07_1.class, args);
context.close();
}
@Bean(initMethod = "init3")
public Bean1 bean1() {
return new Bean1();
}
@Bean(destroyMethod = "destroy3")
public Bean2 bean2() {
return new Bean2();
}
}
Bean1
public class Bean1 implements InitializingBean {
private static final Logger log = LoggerFactory.getLogger(Bean1.class);
@PostConstruct
public void init1() {
log.debug("初始化1");
}
@Override
public void afterPropertiesSet() throws Exception {
log.debug("初始化2");
}
public void init3() {
log.debug("初始化3");
}
}
Bean2
public class Bean2 implements DisposableBean {
private static final Logger log = LoggerFactory.getLogger(Bean2.class);
@PreDestroy
public void destroy1() {
log.debug("销毁1");
}
@Override
public void destroy() throws Exception {
log.debug("销毁2");
}
public void destroy3() {
log.debug("销毁3");
}
}
输出结果:
总结:
Spring 提供了多种初始化手段,除了课堂上讲的 @PostConstruct,@Bean(initMethod) 之外,还可以实现 InitializingBean 接口来进行初始化,如果同一个 bean 用了以上手段声明了 3 个初始化方法,那么它们的执行顺序是
@PostConstruct 标注的初始化方法
InitializingBean 接口的初始化方法
@Bean(initMethod) 指定的初始化方法
与初始化类似,Spring 也提供了多种销毁手段,执行顺序为
@PreDestroy 标注的销毁方法
DisposableBean 接口的销毁方法
@Bean(destroyMethod) 指定的销毁方法
来源:https://blog.csdn.net/qq_61313896/article/details/128791257
标签:Spring,初始化,销毁顺序
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Maven工程打包jar的多种方式
2022-12-15 06:54:46
![](https://img.aspxhome.com/file/2023/6/67686_0s.png)
Java NIO:浅析IO模型_动力节点Java学院整理
2022-01-17 17:07:38
![](https://img.aspxhome.com/file/2023/8/65178_0s.png)
Java开源工具iText生成PDF简单实例
2022-09-12 15:06:54
Java调用Oracle存储过程详解
2022-09-09 03:19:45
Spring @Profile注解详解
2023-04-20 06:26:16
java ThreadGroup的作用及方法详解
2022-02-03 16:49:01
![](https://img.aspxhome.com/file/2023/2/60762_0s.jpg)
Java中的Object类详细介绍
2023-11-23 23:18:46
MybatisPlus字段类型转换的实现示例
2022-12-09 22:29:13
![](https://img.aspxhome.com/file/2023/6/78906_0s.jpg)
一文搞懂Java ScheduledExecutorService的使用
2022-11-22 14:23:35
java中Hibernate缓存形式总结
2023-10-19 15:57:43
C++实现softmax函数的面试经验
2023-06-16 02:07:47
![](https://img.aspxhome.com/file/2023/1/66321_0s.png)
Java实现多任务执行助手
2023-05-17 14:15:30
Java实现简单GUI登录和注册界面
2022-09-02 06:36:21
![](https://img.aspxhome.com/file/2023/2/68202_0s.jpg)
解决Spring boot整合mybatis,xml资源文件放置及路径配置问题
2021-07-07 12:27:20
![](https://img.aspxhome.com/file/2023/9/71209_0s.jpg)
Java结构性设计模式中的装饰器模式介绍使用
2022-04-08 06:30:00
JDK1.8新特性之方法引用 ::和Optional详解
2021-09-13 08:47:33
详解Java中final的用法
2022-09-22 10:20:32
JDBC自定义连接池过程详解
2023-11-17 13:27:55
Java使用ArrayList实现扑克牌的示例代码
2021-10-29 15:17:17
![](https://img.aspxhome.com/file/2023/5/60915_0s.jpg)
一篇文章教你如何用多种迭代写法实现二叉树遍历
2023-12-23 04:03:29