There are lots of initialization options available in spring bean life cycle.
init-method, PostConstruct annotation, afterPropertiesSet, Bean post-initialization and even class constructor. All these can be used for initializing a bean.
I got confused when to use one these over other. Moreover, is there any case we may need to use all these option in a single Bean? If yes please example would be good.
Really looking forward to get some great answers.
The difference between using the constructor and the other options is that the constructor code is the first to be executed, while the other options will be called only after dependencies were injected into the bean (either from @Autowired annotations or the XML file).
Code you write in the constructor will run while the bean's properties are still not initiated. All @Autowired fields would be null. Sometimes this is what you want, but usually you want the code to run after properties are set.
Other than this, I do not see a difference, other then order of execution. I do not think there is a case you would want to have all options in the same class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With