@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.
@PostConstruct and @PreDestroy in 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.
@PostConstruct
public void start() {
System.out.println("Bean is ready!");
}@PreDestroy
public void stop() {
System.out.println("Bean is going to be destroyed.");
}@PostConstruct
public void loadCache() {
cache.loadAll();
}
@PreDestroy
public void clearCache() {
cache.clear();
}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.
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."); } }
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.
@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.