0
0
Spring Bootframework~5 mins

@PostConstruct and @PreDestroy in Spring Boot

Choose your learning style9 modes available
Introduction

@PostConstruct and @PreDestroy help you run code right after a component starts and just before it stops. This is useful to set up or clean up resources automatically.

You want to open a database connection when your app starts and close it before it stops.
You need to load some data or configuration right after your component is ready.
You want to release resources like files or threads before your app shuts down.
You want to log messages when your component starts and stops.
You want to initialize caches or clean them up automatically.
Syntax
Spring Boot
@PostConstruct
public void init() {
    // code to run after bean creation
}

@PreDestroy
public void cleanup() {
    // code to run before bean destruction
}

These annotations are placed on methods inside Spring-managed beans.

The methods should be void and take no arguments.

Examples
This method runs once after the bean is created and dependencies are injected.
Spring Boot
@PostConstruct
public void start() {
    System.out.println("Bean is ready!");
}
This method runs once before the bean is removed from the Spring context.
Spring Boot
@PreDestroy
public void stop() {
    System.out.println("Bean is going to be destroyed.");
}
Use these to manage cache lifecycle automatically.
Spring Boot
@PostConstruct
public void loadCache() {
    cache.loadAll();
}

@PreDestroy
public void clearCache() {
    cache.clear();
}
Sample Program

This Spring component prints messages when it starts and stops. The @PostConstruct method runs after the bean is created. The @PreDestroy method runs before the bean is destroyed, such as when the app shuts down.

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

@Component
public class ResourceHandler {

    @PostConstruct
    public void openResource() {
        System.out.println("Resource opened.");
    }

    @PreDestroy
    public void closeResource() {
        System.out.println("Resource closed.");
    }
}
OutputSuccess
Important Notes

Make sure your Spring application context is properly closed to trigger @PreDestroy methods.

These annotations require the bean to be managed by Spring (like using @Component or @Service).

From Spring 6 and Jakarta EE 9+, use jakarta.annotation.PostConstruct and jakarta.annotation.PreDestroy.

Summary

@PostConstruct runs code right after a Spring bean is ready.

@PreDestroy runs code just before the bean is removed.

Use them to manage setup and cleanup automatically in your Spring apps.