Middle
What do you know about the @PreDestroy annotation?
sobes.tech AI
Answer from AI
The @PreDestroy annotation is used in Spring to invoke a method before a bean is destroyed. This allows performing necessary cleanup operations, closing connections, etc., before the bean's lifecycle ends.
Usage features:
- A method annotated with
@PreDestroyshould not accept arguments. - The method can have any visibility (public, protected, private).
- The method can return
voidor any other type (the return value is ignored). - If multiple methods in a class are annotated with
@PreDestroy, their execution order is not guaranteed. - Exceptions thrown in a
@PreDestroymethod may prevent the Spring container from shutting down properly or destroying other beans.
Alternatives to @PreDestroy:
- Implementing the
DisposableBeaninterface and overriding thedestroy()method. - Specifying a destroy method using the
destroy-methodattribute in Spring XML configuration or the@Beanannotation with thedestroyMethodattribute.
Example of usage:
// Using the @PreDestroy annotation
import javax.annotation.PreDestroy;
public class DatabaseConnection {
private boolean connected = true;
public void connect() {
System.out.println("Database connection established.");
}
@PreDestroy
public void closeConnection() {
if (connected) {
System.out.println("Database connection closed.");
connected = false;
}
}
}
// Using DisposableBean implementation
import org.springframework.beans.factory.DisposableBean;
public class SomeResource implements DisposableBean {
public void openResource() {
System.out.println("Resource opened.");
}
@Override
public void destroy() throws Exception {
System.out.println("Resource closed.");
}
}
| Mechanism | Where is it used? | Advantages | Disadvantages |
|---|---|---|---|
@PreDestroy |
Annotations (Java Config) | Clean code, good readability, JSR-250 standard | Less control over execution order |
DisposableBean |
Programmatically (implement interface) | Transparent, explicit definition | Less readable for many methods |
destroy-method |
XML | Flexibility in configuration | Separation of configuration and logic, becomes outdated |
@Bean(destroyMethod) |
Annotations (Java Config) | Combination of annotations and explicit declaration | Can be verbose for multiple beans |
@PreDestroy is preferred in most modern Spring applications based on Java configuration, as it is the standard JSR-250 way to specify lifecycle callback methods.