Sub topic 6
Destruction Callbacks
This chapter assumes you know core Java, basic Spring dependency injection (@Component, @Bean), and how to start a Spring application. Destruction callbacks let a bean release resources when the container shuts down. Examples are closing a connection pool, flushing a buffer, or stopping a thread.
The three ways to hook in
Spring offers three mechanisms. All of them run when the container closes, before the bean is discarded.
| Mechanism | Where it lives | Notes |
|---|---|---|
| `@PreDestroy` | Method annotation on the bean class | Preferred for your own classes. |
| `DisposableBean.destroy()` | Interface the bean implements | Ties your class to Spring. |
| `destroyMethod` in `@Bean` | Configuration, not the class | Suits third-party classes. |
The next example uses the first two. Each callback prints a line so you can see the order.
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component
public class DemoBean implements InitializingBean, DisposableBean {
public DemoBean() {
System.out.println("constructor");
}
@PostConstruct
void postConstruct() {
System.out.println("@PostConstruct");
}
@Override
public void afterPropertiesSet() {
System.out.println("afterPropertiesSet");
}
@PreDestroy
void preDestroy() {
System.out.println("@PreDestroy");
}
@Override
public void destroy() {
System.out.println("DisposableBean.destroy");
}
}On shutdown, @PreDestroy runs first and DisposableBean.destroy runs second.
Registering callbacks on classes you do not own
You cannot annotate a library class. Name its cleanup method in @Bean instead.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class PoolConfig {
@Bean(initMethod = "open", destroyMethod = "close")
public Pool pool() {
return new Pool();
}
}
class Pool {
public void open() {
System.out.println("pool opened");
}
public void close() {
System.out.println("pool closed");
}
}Spring also infers a destroy method for @Bean methods. If the returned object has a public no-argument close() or shutdown() method, Spring calls it automatically. To turn this off, set destroyMethod = "".
Seeing it run
Destruction runs only when the context closes. In a plain Java program, try-with-resources does this. Spring Boot registers a JVM shutdown hook for you.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
class AppConfig {
}
public class Main {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
ctx.getBean(DemoBean.class);
System.out.println("context running");
}
}
}The output is:
constructor
@PostConstruct
afterPropertiesSet
context running
@PreDestroy
DisposableBean.destroyCommon errors
- Callback never runs. The context was never closed. A
mainmethod that just ends, or a process killed withkill -9, skips destruction. Use try-with-resources,ctx.close(), orregisterShutdownHook(). - Prototype beans are not destroyed. The container creates a prototype bean, hands it over, and stops tracking it. Your code must release its resources. A later chapter covers prototype scope.
- Dependency order. Spring destroys beans in the reverse order of their creation. A bean that depends on another is destroyed before its dependency, so a
@PreDestroymethod can still use its dependencies. - Exceptions. An exception in one destroy method is logged. Shutdown continues with the other beans.
Exercise
A @Bean method returns an object with a public close() method, and you did not set destroyMethod. Will Spring call close() on shutdown? How do you stop it?
Show answer
Yes. Spring infers close() (or shutdown()) as the destroy method for @Bean methods. Set destroyMethod = "" on the annotation to disable it.
Exercise
Your prototype-scoped bean opens a file in @PostConstruct and closes it in @PreDestroy. The file is never closed. Why?
Show answer
The container does not manage the destruction of prototype beans, so it never calls @PreDestroy. The code that obtains the bean must close the file itself.