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

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.


I would suggest that you only use the constructor where possible. There is one very very good reason to do so: testing

When you are going to unit test a Spring bean, you'll want to be able to construct the class with minimum fuss. That means that you should only need to call the constructor, and not have to deal with calling various life-cycle methods on your own. The last thing you want when creating the class to be tested, is to have to know how the object is property initialized.

With Spring's constructor injection support you can easily inject other other beans or project properties into the constructor therefor being able to cover almost every scenario.

Tags:

Java

Spring