1
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?
Sagar Gandhi
  • 925
  • 6
  • 20

1 Answers1

0

@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/

rdas
  • 20,604
  • 6
  • 33
  • 46
  • In PostConstruct it is guaranteed that beans are injected right ? That's why we don't add such bean dependent code in constructor. – Sagar Gandhi Apr 12 '19 at 06:42