@PreDestroy annotation in spring 💥

themayurkumbhar

MAYUR KUMBHAR

Posted on June 13, 2023

@PreDestroy annotation in spring 💥

Need of the @PreDestroy annotation

Sometime in our application we have perform some business operations before the destroy the bean of a class. Such business logic can be performed with @PreDestroy annotation.

How to use?

Below code snippet help in understanding how to configure the @PreDestroy annotation on bean.


@Component
class BeanExample {

    private String name;

    public BeanExample() {
    }

    @PreDestroy 
    public void destroy() {
        System.out.println("Doing destructive operations!");
    }

}
Enter fullscreen mode Exit fullscreen mode

Whenever the bean of BeanExample class about to get destroyed the code in method destroy() will be invoked. Here in case of our example it will output Doing destructive operations! when you close the context annotationConfigApplicationContext.close() by deliberately destroying all the beans.

When to use?

When you want to perform some business operations on the bean during the closing/removing/end of lifecycle you can use the @PreDestroy annotation. Some common use case can be to close the IO resources, release the dependent objects, close acquired connections such as DB connections etc.

Most of the time the spring framework is handling all the resource closing, destruction related activities, but in case you have some scenarios where you want to perform tasks before the bean is destroyed you can use the annotation.

💖 💪 🙅 🚩
themayurkumbhar
MAYUR KUMBHAR

Posted on June 13, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related