SpringBoot中多个PostConstruct注解执行顺序控制
项目场景:
多个类中使用@PostConstruct加载先后顺序
问题描述
有时候Class A中@PostConstruct注解的方法中的代码执行,需要等待Class B中@PostConstruct 注解方法中的代码执行完后,拿到结果,才能执行,也就是中A中某些代码的执行需要依赖B中代码执后的结果,此时就需要B先执行完,再执行A,
解决方案:
方式一:可以在A中先注入B,那么就会先加载B
@Service
@DependsOn("b")
public class A{
@PostConstruct
public void init() {
System.out.println("A Bean init method called");
}
}@Service
public class B{
@PostConstruct
public void init() {
System.out.println("B Bean init method called");
}
}方式二:使用@Order注解
@Service
@Order(2) // 指定执行顺序为2
public class A{
@PostConstruct
public void init() {
System.out.println("A Bean init method called");
}
}@Service
@Order(1) // 指定执行顺序为1
public class B{
@PostConstruct
public void init() {
System.out.println("B Bean init method called");
}
}@Order 值较小的 bean先执行
到此这篇关于SpringBoot中多个PostConstruct注解执行顺序控制的文章就介绍到这了,更多相关SpringBoot PostConstruct 执行顺序内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
- springboot中@PostConstruct注解使用小结
- SpringBoot中@PostConstruct 注解的实现
- springboot启动加载CommandLineRunner @PostConstruct问题
- SpringBoot中的@PostConstruct注解详细解析
- SpringBoot使用@PostConstruct注解导入配置方式
- springboot @PostConstruct无效的解决
- 浅谈SpringBoot中的Bean初始化方法 @PostConstruct
- SpringBoot @PostConstruct和@PreDestroy的使用说明
- SpringBoot @PostConstruct原理用法解析
相关文章
spring-data-jpa+Alibaba Druid多数据源案例实践
本文介绍基于Spring Data JPA与Alibaba Druid配置多数据源的方案,通过定义三个独立数据源、分别设置JPA配置及实体/仓库包,实现订单、用户、详情表的分离管理2025-07-07
springboot报错Invalid bound statement (not found)的解决
本文主要介绍了springboot报错Invalid bound statement (not found)的解决,遇到这种问题通常是没有配置好配置文件,下面就来具体介绍一下解决方法,感兴趣的可以了解一下2025-03-03
IDEA maven compile报错OutOfMemoryError(内存溢出)解决及jvm分析
遇到Maven编译时报OutOfMemoryError错误通常因为默认的堆内存大小不足,本文就来介绍一下OutOfMemoryError(内存溢出)解决,具有一定的参考价值,感兴趣的可以了解一下2024-10-10


最新评论