Backend Development 7 min read

Master Spring Boot Bean Destruction: From DisposableBean to AutoCloseable

This article explains Spring Boot 3 bean destruction techniques—including DisposableBean, @PreDestroy, @Bean destroyMethod, AutoCloseable, and custom inference—provides complete code examples, and announces a continuously updated Spring Boot 3 case collection PDF for developers.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master Spring Boot Bean Destruction: From DisposableBean to AutoCloseable

1. Introduction

Spring manages bean lifecycles and allows custom actions during initialization and destruction via the InitializingBean and DisposableBean interfaces. This article focuses only on bean destruction.

2. Basic Destruction Methods

Implementing DisposableBean

<code>@Component
public class BeanLifecycle03 implements DisposableBean {
    public void destroy() throws Exception {
        System.out.println("DisposableBean destroy...");
    }
}</code>

The container calls destroy() when the bean is destroyed.

Using @PreDestroy

<code>@PreDestroy
public void destroyProcess() {
    System.out.println("des...");
}</code>

The method name and access modifier can be arbitrary, even private .

Configuring destroyMethod on @Bean

<code>// Define bean
public class BeanLifecycle04 {
    public void customDestroy() {
        System.out.println("BeanLifecycle04 customDestroy...");
    }
}

@Bean(destroyMethod = "customDestroy")
BeanLifecycle04 beanLifecycle04() {
    return new BeanLifecycle04();
}</code>

The destroyMethod attribute specifies the callback to execute on bean destruction.

3. Advanced Skills

3.1 @Bean Automatic Destruction

If @Bean is used without specifying destroyMethod , Spring infers a method named close or shutdown . close takes precedence.

<code>public class CommonService {
    public void close() {
        System.out.println("CommonService close...");
    }
    public void shutdown() {
        System.out.println("CommonService shutdown...");
    }
}

@Bean
public CommonService commonService() {
    return new CommonService();
}</code>

3.2 Implementing AutoCloseable

Beans can implement AutoCloseable to have their close() method invoked automatically.

<code>public class BeanLifecycle04 implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("BeanLifecycle04 AutoCloseable close...");
    }
}

@Bean
public BeanLifecycle04 beanLifecycle04() {
    return new BeanLifecycle04();
}</code>

This approach also works when the class is annotated with @Component .

3.3 Destruction Method with Parameters

A destruction method can accept a single boolean parameter when configured via destroyMethod .

<code>public class CommonService {
    public void close(boolean flag) {
        System.out.printf("CommonService close...flag: %s%n", flag);
    }
}

@Bean(destroyMethod = "close")
public CommonService commonService() {
    return new CommonService();
}</code>

Note: The automatic inference mechanism does not support parameterized methods.

3.4 Unified Inference Configuration

To apply the inference mechanism globally, implement a BeanDefinitionRegistryPostProcessor that sets destroyMethodName to (inferred) for selected beans.

<code>public class ProcessInferredBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        for (String name : registry.getBeanDefinitionNames()) {
            BeanDefinition bd = registry.getBeanDefinition(name);
            String className = bd.getBeanClassName();
            if (className != null && className.startsWith("com.pack")) {
                bd.setDestroyMethodName("(inferred)");
            }
        }
    }
}</code>

After this configuration, any bean containing a close or shutdown method will have the appropriate callback invoked during container shutdown.

4. Promotion

The article also announces a continuously updated Spring Boot 3 case collection PDF containing over 80 practical examples, with source code provided to subscribers.

Backend DevelopmentSpring BootAutoCloseablebean lifecyclePreDestroyDisposableBean
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.