SpringBoot中多个PostConstruct注解执行顺序控制
作者:涛哥是个大帅比
本文介绍了SpringBoot中使用多个@PostConstruct注解的方法执行顺序,以解决ClassA依赖ClassB初始化结果的问题,具有一定的参考价值,感兴趣的可以了解一下
项目场景:
多个类中使用@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原理用法解析