Sobes.tech
Junior — Middle

What is the purpose of using the @PreDestroy annotation in Java applications?

sobes.tech AI

Answer from AI

The @PreDestroy annotation is used to designate a method that should be called before a bean is destroyed in the container (for example, in Spring or Java EE). This allows for proper resource release, closing connections, saving state, or performing other cleanup operations.

Example of usage in Spring:

@Component
public class MyBean {

    @PreDestroy
    public void cleanup() {
        // code to release resources
        System.out.println("Bean is being destroyed, performing cleanup");
    }
}

Thus, @PreDestroy helps manage the lifecycle of components and prevent resource leaks.