Why is afterPropertiesSet
of InitializingBean
needed when we have also custom init()
@Bean(initMethod = "init")
or @PostConstuct
?
What actions can I do with one and not do with the other ?
When should I use one and not the other.
All are callbacks triggered after all properties are autowired.

- 1,411
- 2
- 13
- 27
1 Answers
In general, if a bean implements InitializingBean
, first @PostConstruct
is called, then the afterPropertiesSet
and then init-method
.
@PostConstruct
is a JSR-250
annotation while init-method
and InitializingBean
is Spring's tools for bean initialization.
InitializingBean vs. init-method
Choosing between Spring tools, init-method
and destroy-method
is the recommended approach because of no direct dependency to Spring Framework and we can create our own methods. init-method
is a way of calling custom method independent of Spring, if you'll decide to go with some other framework, you can reuse this method.
PostConstruct vs. Spring tools
Spring documentation provides clear explanation about preferable ways of initialization:
To interact with the container's management of the bean lifecycle, you can implement the Spring
InitializingBean
andDisposableBean
interfaces. The container callsafterPropertiesSet()
for the former anddestroy()
for the latter to allow the bean to perform certain actions upon initialization and destruction of your beans.The JSR-250
@PostConstruct
and@PreDestroy
annotations are generally considered best practice for receiving lifecycle callbacks in a modern Spring application. Using these annotations means that your beans are not coupled to Spring specific interfaces.

- 6,881
- 10
- 46
- 64
-
2Could you please clarify the difference between `afterPropertiesSet` and `init-method` – Ida Amit May 21 '18 at 12:26
-
@Alma Shvartz First of all, `afterPropertiesSet` called before `init-method` but making a tight coupling of a bean with Spring Framework. `init-method` is a custom method independent of Spring, if yo'll decide to go with something else, you can reuse the method. – J-Alex May 21 '18 at 12:32
-
@J-Alex, Very nice diagram, with a tiny inaccuracy: `@PostConstruct` is part of `postProcessBeforeInitialization` phase, not a separate action. The details are in https://stackoverflow.com/questions/8519187/spring-postconstruct-vs-init-method-attribute – igor.zh Nov 01 '18 at 20:29