Junior — Middle
How does the @PreDestroy annotation work in Spring and what is its purpose?
sobes.tech AI
Answer from AI
The @PreDestroy annotation in Spring is used to indicate a method that should be called before a bean is destroyed (for example, when the application is shutting down or the bean is removed from the context). This allows for resource cleanup, closing connections, or performing other finalization tasks.
Example:
@Component
public class MyBean {
@PreDestroy
public void cleanup() {
// cleanup code, e.g., closing files or connections
System.out.println("Bean is being destroyed");
}
}
Spring will automatically call the cleanup() method before destroying the bean.