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