Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: init-method, PostConstruct, afterPropertiesSet : when to use one over others?

Tags:

java

spring

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.

like image 348
sabtharishi Avatar asked Aug 27 '14 13:08

sabtharishi


1 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.

like image 87
alexander zak Avatar answered Oct 05 '22 18:10

alexander zak