Spring @PostConstruct and @PreDestroy - Example

Annotations @PostConstruct and @PreDestroy, standardized by JSR-250, are generally considered the best practice for obtaining lifecycle callbacks in a modern Spring application.

  • @PostConstruct annotation defines a method that will run only once, just after the initialization of bean.
  • @PreDestroy annotation defines a method that will run only once, just before Spring removes the bean from the application context.

Complete Example 

We are creating a simple maven project. You could clone the code from our GitHub repo.

Final Project Directory


Complete pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<
modelVersion>4.0.0</modelVersion>

<
groupId>com.knf.dev.demo</groupId>
<
artifactId>postconstruct-predestroy-example</artifactId>
<
version>1.0-SNAPSHOT</version>

<
properties>
<
maven.compiler.source>17</maven.compiler.source>
<
maven.compiler.target>17</maven.compiler.target>
<
project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</
properties>
<
dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.0</version>
</dependency>
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>2.1.1</version>
</dependency>

</
dependencies>

</
project>

We have to add jakarta.annotation dependency to use these annotations.


Create Component class

Create MyComponent class and create methods annotated with @PostConstruct and @PreDestroy. Also, we have one printMessage() method. 
Here we are using Annotation-based configuration.
package com.knf.dev.demo;


import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {


@PostConstruct
public void postConstruct() throws Exception {
System.out.println("After bean initialization");
}

@PreDestroy
public void preDestroy() {
System.out.println("Perform destructive task or release resources.");
}

public void printMessage() {
System.out.println("Hello");
}

}


Create Config

package com.knf.dev.demo;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class Config {

}

Spring provides a mechanism to identify application component explicitly through the @ComponentScan annotation. We are not passing arguments to @ComponentScan, letting Spring to scan the current package and all of its sub-packages.


Create main class - Application.java 

package com.knf.dev.demo;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

public class Application {

public static void main(String[] args) {

AbstractApplicationContext context =
new AnnotationConfigApplicationContext(Config.class);
MyComponent myComponent = context.getBean(MyComponent.class);
myComponent.printMessage();

context.close();
}
}

The AbstractApplicationContext.close() method will close the application context, and destroying all cached singleton beans.

Console Output: 

After bean initialization

Hello

Perform destructive task or release resources.

Source code  

Are you preparing for Spring certification or preparing for Spring interview? Then below examples are interesting for you!

Spring Core Annotations

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete