项目场景:

多个类中使用@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先执行 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐