Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Why is afterPropertiesSet of InitializingBean needed when we have also custom init() or @PostConstuct

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.

like image 540
Ida Amit Avatar asked Nov 29 '22 08:11

Ida Amit


1 Answers

In general, if a bean implements InitializingBean, first @PostConstruct is called, then the afterPropertiesSet and then init-method.

Spring bean lifecycle

@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 and DisposableBean interfaces. The container calls afterPropertiesSet() for the former and destroy() 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.

like image 66
J-Alex Avatar answered Dec 04 '22 14:12

J-Alex