What if your app could prepare and clean up itself perfectly every time, without you lifting a finger?
Why @PostConstruct and @PreDestroy in Spring Boot? - Purpose & Use Cases
Imagine you have a Java class that needs to open a database connection when it starts and close it when it stops. You write code to do this manually in many places, like constructors and shutdown hooks.
Manually managing setup and cleanup is tricky. You might forget to close resources, causing memory leaks. It's hard to keep track of when to run this code, especially as your app grows.
@PostConstruct and @PreDestroy let you mark methods to run automatically right after creation and just before destruction of a Spring bean. This keeps setup and cleanup neat and reliable.
public class MyService {
public MyService() {
openConnection();
}
public void close() {
closeConnection();
}
}import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; public class MyService { @PostConstruct public void init() { openConnection(); } @PreDestroy public void cleanup() { closeConnection(); } }
This makes your app safer and easier to maintain by automating resource setup and cleanup at the right times.
Think of a coffee machine that automatically heats water when turned on and cleans itself before turning off. @PostConstruct and @PreDestroy do the same for your app's resources.
Manual resource management is error-prone and hard to track.
@PostConstruct runs setup code after bean creation.
@PreDestroy runs cleanup code before bean destruction.