简体   繁体   English

Spring @PostConstruct执行顺序?

[英]Spring @PostConstruct execution order?

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(){

        }
}

Issue : Intermittent 问题:间歇性

Description : Now in my case, PostCostruct for User is getting called first. 描述 :现在在我的情况下,首先调用PostCostruct for User。 MyOtherBean PostConstruct is called after that which actually populate values. 之后调用MyOtherBean PostConstruct实际填充值。

When User PostConstruct tries getValues it returns null and results into NPE. 当User PostConstruct尝试getValues时,它返回null并导致NPE。

Questions 问题

  1. Any way to avoid this ? 有什么办法可以避免这个吗
  2. What is the correct standard way to avoid such dependency? 避免这种依赖的正确标准方法是什么?

@PostConstruct is called after Bean construction, setting properties but before injecting into context. @PostConstruct在Bean构造之后调用,在注入上下文之前设置属性。 Ideally you should be putting any code there that depends on other beans - since those beans might not have been initialized yet. 理想情况下,您应该在那里放置任何依赖于其他bean的代码 - 因为这些bean可能尚未初始化。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM