Junior — Middle
Could you explain what the @PreDestroy annotation means in Java and how it is used?
sobes.tech AI
Answer from AI
The @PreDestroy annotation in Java is used to designate a method that should be called before a bean or object managed by a container (such as in Spring or Java EE) is destroyed.
This allows for resource cleanup, closing connections, saving state, or performing other final actions before the object is removed from memory.
Example of usage in Spring:
@Component
public class MyBean {
@PreDestroy
public void cleanup() {
// cleanup code, e.g., closing connections
System.out.println("Bean is being destroyed");
}
}
When the Spring container finishes working with this bean, it will automatically invoke the cleanup() method.