Spring DisposableBean Guide

In Spring, DisposableBean is an interface used to execute specific logic before a bean is destroyed, such as releasing resources or closing connections.

The DisposableBean interface has only one method, destroy(), which Spring container automatically calls when a bean is destroyed. Developers can implement the DisposableBean interface and write their own destruction logic within the destroy() method.

Here is an example of how to use DisposableBean:

import org.springframework.beans.factory.DisposableBean;

public class MyBean implements DisposableBean {

    @Override
    public void destroy() throws Exception {
        // 执行销毁逻辑,比如关闭连接、释放资源等
    }
}

In the example above, when the Bean MyBean is being destroyed, Spring will automatically call the destroy() method to execute the destruction logic. Developers can write their own destruction logic in the destroy() method, such as closing database connections or releasing file resources.

Instead of implementing the DisposableBean interface, you can also use the @PreDestroy annotation to mark the destruction method. The method marked with the @PreDestroy annotation will be called before the bean is destroyed, serving as an alternative to implementing the DisposableBean interface.

import javax.annotation.PreDestroy;

public class MyBean {

    @PreDestroy
    public void destroy() throws Exception {
        // 执行销毁逻辑,比如关闭连接、释放资源等
    }
}

Whether implementing the DisposableBean interface or using the @PreDestroy annotation, you can execute specific logic before a Bean is destroyed to ensure proper release and closure of resources.

bannerAds