简体   繁体   中英

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. MyOtherBean PostConstruct is called after that which actually populate values.

When User PostConstruct tries getValues it returns null and results into 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. Ideally you should be putting any code there that depends on other beans - since those beans might not have been initialized yet.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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