【问题标题】:Spring @PostConstruct execution order?Spring @PostConstruct 执行顺序?
【发布时间】:2019-04-12 06:32:58
【问题描述】:
Class User
{

        @Autowired
        private MyOtherBean;

        @PostConstruct
        public void init(){
                for(MyObject value : myOtherBean.getValues()){

                }
        }
}



Class MyOtherBean
{
        @Autowired
        private MyOtherBean1;

        @PostConstruct
        public void init(){
                MyOtherBean1.populateValues();
        }

        public Collection<MyObject> getValues(){

        }
}

问题:间歇性

说明: 现在就我而言,首先调用 PostCostruct for User。 MyOtherBean PostConstruct 在实际填充值之后调用。

当 User PostConstruct 尝试 getValues 时,它返回 null 并导致 NPE。

问题

  1. 有什么办法可以避免这种情况?
  2. 避免这种依赖的正确标准方法是什么?

【问题讨论】:

    标签: java spring spring-mvc dependency-injection postconstruct


    【解决方案1】:

    @PostConstruct 在 Bean 构造之后调用,设置属性但在注入上下文之前。理想情况下,您应该将任何依赖于其他 bean 的代码放在那里 - 因为这些 bean 可能尚未初始化。

    https://hobione.wordpress.com/2009/04/22/jsf-postconstruct/

    【讨论】:

    • 在 PostConstruct 中保证注入 bean 对吗?这就是为什么我们不在构造函数中添加这种依赖 bean 的代码。
    猜你喜欢
    • 1970-01-01
    • 2016-10-30
    • 2015-12-17
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多