Sub topic 6
Destruction callbacks
This chapter assumes you know core Java annotations, basic Spring dependency injection (@Component, @Bean, @Configuration), and how to start a Spring or Spring Boot application. It covers how a bean is cleaned up when the container closes, which hooks you can use, and why some beans are never cleaned up by the container at all.
Why destruction callbacks exist
Many beans hold resources that the JVM does not release on its own: connection pools, thread pools, open files, sockets, scheduled tasks, or registrations with an external system. A destruction callback is a method the container calls on a bean just before it discards the bean. You use it to release those resources in an orderly way.
Destruction callbacks run when the container shuts down. They do not run when your code stops using a bean or when the garbage collector reclaims it. If the context never closes, the callbacks never run.
The three ways to declare a destruction callback
Spring offers three mechanisms. They do the same job and differ in how much they tie your class to Spring.
| Mechanism | Where you declare it | Ties class to Spring? | Typical use |
|---|---|---|---|
| `@PreDestroy` | Annotation on a method | No, it is a Jakarta standard annotation | Your own classes |
| `DisposableBean.destroy()` | Implement an interface | Yes | Framework-style code |
| `destroyMethod` on `@Bean` | Attribute naming a method | No | Third-party classes you cannot edit |
@PreDestroy
Annotate a no-argument method with @PreDestroy. The method may have any visibility and must not take parameters. Spring discovers it through a BeanPostProcessor that is registered automatically in annotation-based contexts.
DisposableBean
Implement org.springframework.beans.factory.DisposableBean and its destroy() method. This works without any annotation processing, but it couples the class to Spring, so most teams prefer @PreDestroy.
destroyMethod on @Bean
When you cannot modify a class, name the method in the @Bean definition. The example below registers open and close on a class defined elsewhere in the project.
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");
}
}Inferred destroy methods
For @Bean methods, Spring has a default behavior called destroy method inference. If a bean has a public no-argument method named close or shutdown, Spring calls it on shutdown even if you did not set destroyMethod. This is why a DataSource or ExecutorService returned from a @Bean method is closed automatically.
To turn this off, for example when the object is shared and managed elsewhere, set destroyMethod = "":
@Bean(destroyMethod = "")
public SharedClient sharedClient() {
return LegacyRegistry.lookupSharedClient();
}Inference applies to @Bean methods only. A class registered through @Component scanning does not get its close() called unless it implements AutoCloseable/Closeable through some other route or you add @PreDestroy.
Seeing the order
The bean below uses two of the three mechanisms, plus the initialization callbacks, and prints a line in each.
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");
}
}A plain Java program can start and close a context. Try-with-resources calls close() on the context, which triggers the destruction callbacks.
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.destroyWhen a bean uses several destruction mechanisms, Spring runs them in a fixed order:
- Methods annotated with
@PreDestroy. destroy()fromDisposableBean.- A custom
destroyMethodconfigured in the bean definition.
This mirrors the initialization order (@PostConstruct, then afterPropertiesSet, then initMethod). If the same method name appears in more than one mechanism, Spring calls it only once.
When the container calls them
A destruction callback runs only when the context is closed. How that happens depends on how you run the application.
- Spring Boot registers a JVM shutdown hook for you. Stopping the process with
SIGTERMorCtrl+Ccloses the context and runs the callbacks. - A plain
ApplicationContextcloses when you callclose(), use try-with-resources as above, or callregisterShutdownHook()on aConfigurableApplicationContextso the JVM closes it on exit. - A web application in a servlet container closes the context when the application is undeployed or the container stops.
Order across beans
Spring destroys beans in the reverse order of their dependencies. If OrderService depends on DataSource, then OrderService is destroyed first and DataSource afterwards. This lets a bean use its dependencies safely inside its own destruction callback. The same dependency information that decided creation order decides destruction order.
Scope decides whether callbacks run
The container manages the full lifecycle only for beans it keeps a reference to.
- Singleton beans: the container holds them for the life of the context, so destruction callbacks always run at close.
- Request, session, and application scoped beans: the scope implementation tracks them and calls destruction callbacks when the request ends, the session expires, or the servlet context shuts down.
- Prototype beans: the container creates the instance, runs initialization callbacks, hands it to the caller, and forgets it. It never calls destruction callbacks on a prototype bean.
The reason is practical. A prototype bean may be created thousands of times, and the container has no way to know when each caller is finished with an instance. Holding references to all of them would leak memory.
This leads to a common error. A prototype bean with a @PreDestroy method compiles and looks correct, but the method silently never runs.
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class Connection {
@PreDestroy
void release() {
System.out.println("never printed by the container");
}
}The fix is to make the caller responsible. The code that obtains the prototype instance calls an explicit method, such as close(), when it is done. Alternatively, the singleton that creates the prototypes can keep a list of them and release them in its own @PreDestroy. Another option is a custom bean post processor that records prototype instances for later cleanup.
Common errors
- Context never closed. In tests and small
mainprograms, the callbacks do not appear because the JVM exits without closing the context. Use try-with-resources or a shutdown hook. - Wrong signature. A
@PreDestroymethod with parameters causes an error at startup. Spring rejects it because it cannot supply arguments. - Exceptions in a callback. Spring logs an exception thrown from a destruction callback and continues destroying the remaining beans. One failing bean does not stop the rest, but its cleanup is incomplete.
- Blocking work. A callback that waits on a thread pool that has already stopped can hang shutdown. Check what a bean depends on before using it in cleanup.
- Lazy beans never created. A lazy singleton that was never requested was never instantiated, so it has no destruction callback to run.
Exercise
A @Component class with @Scope("prototype") has a @PreDestroy method that closes a file. The application creates 100 instances through an ObjectProvider and then shuts down cleanly. How many times is the @PreDestroy method called by the container, and what should you do to close the files?
Show answer
Zero times. The container does not track prototype instances after handing them out, so it never calls their destruction callbacks. The code that obtains each instance must close it explicitly (for example by calling a close() method, ideally in a try-finally block). Alternatively, the singleton that creates the instances can keep references and close them in its own @PreDestroy.
Exercise
A bean implements DisposableBean, has a @PreDestroy method, and is registered with @Bean(destroyMethod = "stop"). In what order do the three run at shutdown?
Show answer
First the @PreDestroy method, then DisposableBean.destroy(), then stop().