当前位置: 代码网 > it编程>编程语言>Java > SpringBoot中多个PostConstruct注解执行顺序控制

SpringBoot中多个PostConstruct注解执行顺序控制

2025年08月07日 Java 我要评论
项目场景:多个类中使用@postconstruct加载先后顺序问题描述有时候class a中@postconstruct注解的方法中的代码执行,需要等待class b中@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 执行顺序内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com