Search This Blog

Spring 5 InitializingBean and DisposableBean Example

In Spring, 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 let the bean 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.

For bean implemented InitializingBean, it will run afterPropertiesSet() after all bean properties have been set.

For bean implemented DisposableBean, it will run destroy() after Spring container is released the bean.

In this article, we use the latest release of Spring 5.1.0.RELEASE version to demonstrate this example.

Spring InitializingBean and DisposableBean Example

In real time projects, we populate a database table with some records during application startup and will delete records from same database table during application shutdown.

In this example, we will populate the in-memory List data structure with few user objects during application startup using afterPropertiesSet() method. We will also delete user objects from List during application shutdown using destroy() method.

Tools and technologies used

Spring Framework - 5.1.0.RELEASE

JDK - 8 or later

Maven - 3.2+

IDE - Eclipse Mars/STS

Create a Simple Maven Project

Create a simple maven project using your favorite IDE and refer below section for packaging structure. If you are new to maven then read this article How to Create a Simple Maven Project.

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. For details, see Using @PostConstruct and @PreDestroy.