Spring core. Default @Bean destroy method

Spring core. Default @Bean destroy method

In Spring Framework, when defining beans either with XML configuration or using Java configuration with @Bean annotation, the framework provides a way to specify a destroy method. The destroy method is called when the application context is shut down and is used for cleanup activities.

Default Destroy Method

If you don't specify a destroy method, Spring will attempt to detect an appropriate method. For example, it will call the close or shutdown method if it finds one on your bean class. This is a part of the 'convention over configuration' philosophy that Spring follows. This means if your bean class has a method named close or shutdown, that method will be automatically called upon the destruction of the bean without you explicitly specifying it.

Using @Bean Annotation

When you define a bean with the @Bean annotation, you can specify a destroy method like this:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean(destroyMethod = "customDestroyMethod")
    public MyBean myBean() {
        return new MyBean();
    }
}

class MyBean {
    public void customDestroyMethod() {
        // cleanup code
    }
}

In this example, customDestroyMethod will be called when the application context is closed, and the MyBean instance is destroyed.

No Destroy Method

If you have no need for a specific destroy method, you don't need to specify anything. Spring will take care of the lifecycle of the bean, and if it detects a close or shutdown method, it will call it; otherwise, no action is taken.

XML Configuration

In XML configuration, the destroy method is specified with the destroy-method attribute:

<bean id="myBean" class="com.example.MyBean" destroy-method="customDestroyMethod"/>

@PreDestroy Annotation

Another approach to define a cleanup or destroy method is by using the @PreDestroy annotation. Methods annotated with @PreDestroy are automatically called before the bean is destroyed:

import javax.annotation.PreDestroy;

public class MyBean {

    @PreDestroy
    public void cleanup() {
        // cleanup code
    }
}

This method is particularly useful as it keeps the destroy logic close to the bean itself and doesn't require you to modify your configuration.

Remember, the exact timing of when the destroy method is called depends on the lifecycle of the application context and how you manage it.


More Tags

code-translation kernel historian readline android-holo-everywhere ireport .net-2.0 amazon-cloudwatch gpuimage javacv

More Java Questions

More Physical chemistry Calculators

More Organic chemistry Calculators

More Everyday Utility Calculators

More Pregnancy Calculators