Spring InitializingBean and DisposableBean Example

In this tutorial, we will explore how to use the InitializingBean and DisposableBean interfaces in Spring for bean lifecycle management. These interfaces provide hooks for performing actions during bean initialization and destruction.

Introduction

Spring beans have a lifecycle that includes phases such as instantiation, property setting, initialization, and destruction. By implementing the InitializingBean and DisposableBean interfaces, we can hook into the initialization and destruction phases to perform custom logic.

  • InitializingBean: The afterPropertiesSet() method is called after the bean's properties have been set.
  • DisposableBean: The destroy() method is called before the bean is destroyed.

Why Use InitializingBean and DisposableBean?

  • InitializingBean: Useful for performing custom initialization logic after all properties have been set.
  • DisposableBean: Useful for performing custom cleanup logic before the bean is destroyed.

Project Setup

Step 1: Create a Spring Boot Project

  1. Using Spring Initializr:

    • Go to Spring Initializr.
    • Select the following options:
      • Project: Maven Project
      • Language: Java
      • Spring Boot: 3.3.0
    • Add dependencies:
      • Spring Web
    • Click on Generate to download the project.
  2. Import the project into your favorite IDE (Eclipse, IntelliJ, etc.).

Step 2: Create Bean Classes Implementing InitializingBean and DisposableBean

Create two classes MyInitializingBean and MyDisposableBean which will implement InitializingBean and DisposableBean respectively.

MyInitializingBean.java

package net.javaguides.spring.lifecycle;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class MyInitializingBean implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        // Custom initialization logic
        System.out.println("MyInitializingBean: afterPropertiesSet method called");
    }
}

MyDisposableBean.java

package net.javaguides.spring.lifecycle;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

@Component
public class MyDisposableBean implements DisposableBean {

    @Override
    public void destroy() throws Exception {
        // Custom cleanup logic
        System.out.println("MyDisposableBean: destroy method called");
    }
}

Step 3: Create the Main Application Class

Create a main class to run your Spring Boot application.

SpringLifecycleApplication.java

package net.javaguides.spring.lifecycle;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringLifecycleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringLifecycleApplication.class, args);
    }
}

Step 4: Run the Application

Run the SpringLifecycleApplication class as a Java application. You should see the following output in the console:

MyInitializingBean: afterPropertiesSet method called

Step 5: Shut Down the Application

When you shut down the application (e.g., by stopping the Spring Boot application in your IDE), you should see the following output in the console:

MyDisposableBean: destroy method called

Explanation

  • MyInitializingBean: Implements InitializingBean and overrides the afterPropertiesSet method to include custom initialization logic. This method is called after the properties of the bean have been set.
  • MyDisposableBean: Implements DisposableBean and overrides the destroy method to include custom cleanup logic. This method is called when the Spring container is shutting down.

Best Practices

  • Use Annotations: For most scenarios, it is better to use @PostConstruct and @PreDestroy annotations for initialization and destruction callbacks as they are more concise and easier to manage.
  • Avoid Overuse: Do not overuse these interfaces. Use them only when you need custom logic that cannot be handled by other means (like @PostConstruct and @PreDestroy).

Conclusion

In this tutorial, we have learned how to use the InitializingBean and DisposableBean interfaces in Spring for managing bean lifecycle events. We have seen how to create a simple Spring Boot application to demonstrate their usage and discussed best practices for their use.

This approach ensures that your beans are properly initialized and cleaned up, making your application more robust and maintainable.

Additional Resources

Comments