@PreDestroy in Spring: What It Is and How It Works
@PreDestroy annotation marks a method to be called just before a bean is removed from the container. It is used to release resources or perform cleanup tasks before the bean is destroyed.How It Works
The @PreDestroy annotation tells Spring to run a specific method right before the bean is destroyed. Think of it like cleaning up your workspace before leaving: you close files, turn off devices, and tidy up. Similarly, Spring calls the method annotated with @PreDestroy to release resources like open files, database connections, or threads.
This happens automatically when the Spring container shuts down or when the bean is removed. The method must have no parameters and usually returns void. This ensures your application cleans up properly and avoids resource leaks.
Example
This example shows a Spring bean with a method annotated by @PreDestroy. When the application context closes, the cleanup method runs automatically.
import jakarta.annotation.PreDestroy; import org.springframework.stereotype.Component; @Component public class ResourceBean { public void useResource() { System.out.println("Using resource..."); } @PreDestroy public void cleanup() { System.out.println("Cleaning up resource before bean destruction."); } }
When to Use
Use @PreDestroy when your Spring bean holds resources that need explicit cleanup. For example:
- Closing database connections
- Stopping background threads
- Releasing file handles or network sockets
This ensures your app frees resources properly and avoids memory leaks or locked files when shutting down or reloading beans.
Key Points
@PreDestroymarks a method to run before bean destruction.- The method must have no arguments and usually returns void.
- It helps clean up resources like files, connections, or threads.
- Spring calls it automatically when the context closes or bean is removed.
- Use it to avoid resource leaks and ensure graceful shutdown.
Key Takeaways
@PreDestroy runs a cleanup method before a Spring bean is destroyed.