Junior — Middle
How often does the method annotated with @PreDestroy execute when a Spring bean's lifecycle ends?
sobes.tech AI
Answer from AI
The method annotated with @PreDestroy in Spring is called once at the end of the bean's lifecycle, just before it is destroyed by the Spring container.
This occurs in the following cases:
- When the application or Spring context is stopped.
- When a bean's scope is removed (for example, for session or request scope).
@PreDestroy is used for resource cleanup, closing connections, saving state, and other finalization operations.
Example:
@Component
public class MyBean {
@PreDestroy
public void cleanup() {
System.out.println("Bean is being destroyed");
// resource cleanup
}
}
Thus, the method with @PreDestroy is triggered exactly once during the bean's lifecycle, immediately before its destruction.