Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

Spring @PostConstruct and @PreDestroy Annotation with Example

In the Spring framework, @PostConstruct and @PreDestroy annotations are used to mark methods for post-construction and pre-destruction lifecycle events, respectively. These annotations allow you to perform specific actions immediately after a bean is initialized and just before it is removed from the container.

@PostConstruct

This annotation is used on a method that needs to be executed after the bean is fully initialized. This method will get executed after all the bean properties have been set.

@PreDestroy

This annotation is used on a method that needs to be executed just before the bean is removed from the container and destroyed.

Example

Let's demonstrate the use of these annotations:

  • Maven Dependency: Ensure you have the required Spring dependencies in your pom.xml.

  • Bean Class with Lifecycle Methods:

@Component
public class MyBean {

    public MyBean() {
        System.out.println("Constructor of MyBean called.");
    }

    @PostConstruct
    public void init() {
        System.out.println("MyBean @PostConstruct called.");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("MyBean @PreDestroy called.");
    }
}
  • Spring Configuration Class:
@Configuration
@ComponentScan(basePackages = "your.base.package")
public class AppConfig {

    // Other beans and configurations
}
  • Main Application:
public class Application {
    public static void main(String[] args) {
        try (AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class)) {
            MyBean myBean = context.getBean(MyBean.class);
            // Use the bean
        }
    }
}

When you run the above application, you will see the following output:

Constructor of MyBean called.
MyBean @PostConstruct called.
...
MyBean @PreDestroy called.

Explanation:

  • When the Spring context starts, it creates an instance of MyBean which calls the constructor.
  • After all properties of MyBean have been initialized, the init method annotated with @PostConstruct is executed.
  • When the application context closes (or is refreshed), the destroy method annotated with @PreDestroy is executed.

It's worth noting that for these lifecycle annotations to work, the bean should be managed by the Spring container. If you manually instantiate the bean using the new keyword, these lifecycle methods won't get executed.

  1. Using @PostConstruct and @PreDestroy in Spring:

    • Description: The @PostConstruct annotation is used to indicate a method that should be invoked after the bean has been constructed and all dependencies have been injected. On the other hand, @PreDestroy is used to mark a method that should be called just before the bean is removed from the container.

    • Code Example:

      public class MyBean {
      
          @PostConstruct
          public void init() {
              // Initialization logic
          }
      
          @PreDestroy
          public void destroy() {
              // Destruction logic
          }
      }
      
  2. @PostConstruct and @PreDestroy lifecycle annotations explained:

    • Description: @PostConstruct is a method-level annotation indicating that the annotated method should be invoked after the bean has been constructed. @PreDestroy is used to mark a method that should be called just before the bean is removed.

    • Code Example:

      public class MyBean {
      
          @PostConstruct
          public void init() {
              // Initialization logic
          }
      
          @PreDestroy
          public void destroy() {
              // Destruction logic
          }
      }
      
  3. Initializing and destroying beans with Spring annotations:

    • Description: Spring provides @PostConstruct and @PreDestroy annotations to initialize and destroy beans. Methods annotated with @PostConstruct are invoked after bean construction, and methods annotated with @PreDestroy are called before the bean is destroyed.

    • Code Example:

      public class MyBean {
      
          @PostConstruct
          public void init() {
              // Initialization logic
          }
      
          @PreDestroy
          public void destroy() {
              // Destruction logic
          }
      }
      
  4. Order of execution for @PostConstruct and @PreDestroy in Spring:

    • Description: In Spring, the order of execution for @PostConstruct and @PreDestroy annotations is well-defined. @PostConstruct methods are executed after bean construction, while @PreDestroy methods are called before bean destruction.

    • Code Example:

      public class MyBean {
      
          @PostConstruct
          public void init() {
              // Initialization logic
          }
      
          @PreDestroy
          public void destroy() {
              // Destruction logic
          }
      }
      
  5. Common use cases for @PostConstruct and @PreDestroy in Spring:

    • Description: @PostConstruct is commonly used for initializing resources, setting default values, or performing other setup tasks. @PreDestroy is often used for releasing resources, closing connections, or performing cleanup before a bean is destroyed.

    • Code Example:

      public class MyBean {
      
          @PostConstruct
          public void init() {
              // Initialization logic
          }
      
          @PreDestroy
          public void destroy() {
              // Destruction logic
          }
      }
      
  6. Managing bean lifecycle with annotations in Spring:

    • Description: Spring allows you to manage the lifecycle of beans using annotations like @PostConstruct and @PreDestroy. These annotations provide hooks for custom initialization and destruction logic.

    • Code Example:

      public class MyBean {
      
          @PostConstruct
          public void init() {
              // Initialization logic
          }
      
          @PreDestroy
          public void destroy() {
              // Destruction logic
          }
      }
      
  7. Examples of initialization and destruction methods in Spring:

    • Description: Examples of initialization methods using @PostConstruct include setting up default values or establishing connections. Examples of destruction methods using @PreDestroy include releasing resources, closing connections, or performing cleanup.

    • Code Example:

      public class MyBean {
      
          @PostConstruct
          public void init() {
              // Initialization logic
          }
      
          @PreDestroy
          public void destroy() {
              // Destruction logic
          }
      }
      
  8. Spring bean lifecycle hooks with annotations:

    • Description: Spring bean lifecycle hooks using annotations (@PostConstruct and @PreDestroy) provide a convenient way to execute custom initialization and destruction logic, contributing to effective bean management.

    • Code Example:

      public class MyBean {
      
          @PostConstruct
          public void init() {
              // Initialization logic
          }
      
          @PreDestroy
          public void destroy() {
              // Destruction logic
          }
      }