Sub topic 10
Bean lifecycle: initialization and destruction callbacks
This chapter assumes you know how beans are defined (@Component, @Bean), how constructor injection works, and what an ApplicationContext is. It also assumes you know the difference between singleton and prototype scope. Here you will see the steps Spring runs between creating a bean and discarding it, and where your own code can hook into them.
Why lifecycle callbacks exist
A constructor runs before Spring has finished wiring the object. With constructor injection, the dependencies are already available inside the constructor. But some work should wait until the bean is fully assembled and the container is ready for it:
- Opening a connection or a file.
- Warming a cache.
- Validating configuration values.
- Starting a background thread.
The matching cleanup, such as closing connections, flushing buffers, or stopping threads, has to run when the container shuts down.
Spring offers callbacks for both moments. The container calls them at fixed points in a bean's life, so you don't call them yourself.
The order of events for a singleton
For a singleton bean, Spring performs these steps in order.
- Instantiate the object by calling its constructor or
@Beanmethod. - Inject dependencies (setter and field injection happen here).
- Call
*Awareinterfaces such asBeanNameAwareandApplicationContextAware, if the bean implements them. - Run
BeanPostProcessor.postProcessBeforeInitializationfor every registered post-processor. - Run the initialization callbacks.
- Run
BeanPostProcessor.postProcessAfterInitialization. This is where Spring wraps beans in proxies for features such as@Transactional. - The bean is ready for use.
- On context close, run the destruction callbacks.
Three ways to declare callbacks
Spring supports three mechanisms for each phase.
| Mechanism | Initialization | Destruction | Ties your class to Spring? |
|---|---|---|---|
| Annotations (`jakarta.annotation`) | `@PostConstruct` | `@PreDestroy` | No, they are standard Jakarta annotations |
| Spring interfaces | `InitializingBean.afterPropertiesSet()` | `DisposableBean.destroy()` | Yes |
| Bean definition attributes | `@Bean(initMethod = "...")` | `@Bean(destroyMethod = "...")` | No |
Annotations are the usual choice for classes you write. The @Bean attributes suit third-party classes whose source you can't edit. The Spring interfaces work, but they couple your code to the framework, so most teams avoid them in application code.
In Spring 6 and Spring Boot 3, the annotations live in the jakarta.annotation package. Older code uses javax.annotation, which no longer works with these versions.
A callback method should have no parameters. It can have any visibility, including package-private or private. It normally returns void.
Seeing the order
You can combine all three mechanisms on one bean and watch the order. This program is complete and runs with spring-context on the classpath.
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class LifecycleDemo {
public static class Connection implements InitializingBean, DisposableBean {
public Connection() {
System.out.println("1 constructor");
}
@PostConstruct
void postConstruct() {
System.out.println("2 @PostConstruct");
}
@Override
public void afterPropertiesSet() {
System.out.println("3 afterPropertiesSet");
}
void customInit() {
System.out.println("4 init-method");
}
@PreDestroy
void preDestroy() {
System.out.println("5 @PreDestroy");
}
@Override
public void destroy() {
System.out.println("6 destroy");
}
void customDestroy() {
System.out.println("7 destroy-method");
}
}
@Configuration
public static class Config {
@Bean(initMethod = "customInit", destroyMethod = "customDestroy")
public Connection connection() {
return new Connection();
}
}
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext(Config.class)) {
System.out.println("context ready");
}
}
}The output shows the fixed order within each phase:
1 constructor
2 @PostConstruct
3 afterPropertiesSet
4 init-method
context ready
5 @PreDestroy
6 destroy
7 destroy-methodInitialization order is @PostConstruct, then InitializingBean, then the custom init method. Destruction uses the same order: @PreDestroy, then DisposableBean, then the custom destroy method.
If the same method name is registered through more than one mechanism, Spring runs it only once.
Using injected dependencies in a callback
The main reason to use @PostConstruct rather than the constructor is that Spring has finished injecting dependencies by the time it runs. With constructor injection the dependencies are available in both places. With field or setter injection, they are available only in the callback.
import jakarta.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Component;
interface PriceLoader {
Map<String, Double> loadAll();
}
@Component
public class PriceCache {
private final PriceLoader loader;
private final Map<String, Double> prices = new HashMap<>();
public PriceCache(PriceLoader loader) {
this.loader = loader;
}
@PostConstruct
void warmUp() {
prices.putAll(loader.loadAll());
}
public Double priceOf(String sku) {
return prices.get(sku);
}
}Keep the constructor free of side effects. It should only store its arguments. Put work that touches the outside world in the callback.
Destruction depends on scope and on a clean shutdown
Destruction callbacks run only in some situations.
- Singletons. Spring calls destruction callbacks when the context closes. Closing means
ctx.close(), try-with-resources, or a shutdown hook. - Prototypes. Spring creates the object, hands it over, and forgets it. It never calls
@PreDestroyon a prototype bean. Your code must release the resources of prototype beans. - Plain
mainprograms. If you never close the context, nothing is destroyed. Callctx.registerShutdownHook()to close it when the JVM exits normally. - Spring Boot. Boot registers the shutdown hook for you.
- Forced termination. If the process is killed with
kill -9or crashes, no callbacks run. Don't rely on@PreDestroyfor data you can't afford to lose.
Inferred destroy methods in `@Bean`
For @Bean methods, Spring has a convenience. If you don't set destroyMethod, it looks for a public no-argument method named close or shutdown on the returned object, and calls it on shutdown. That is why a DataSource or an ExecutorService exposed as a bean is cleaned up without extra configuration.
To turn this off, for example when the object is shared and owned elsewhere, set the attribute to an empty string:
@Bean(destroyMethod = "")
public ExecutorService sharedExecutor() {
return SharedExecutors.global();
}Gotchas
Singletons are created eagerly
By default, Spring creates every singleton when the context starts, so initialization callbacks run at startup. An exception thrown from @PostConstruct fails the whole context startup. This is useful for failing fast on bad configuration, but a flaky network call in an init method can stop your application from starting.
Mark a bean @Lazy to delay creation, and its init callback, until first use.
Proxies are not ready during initialization
Proxies for @Transactional, @Async, and similar annotations are applied in step 6, after initialization callbacks. Inside @PostConstruct, calling your own @Transactional method therefore does not start a transaction.
If you need work that depends on proxies, listen for ContextRefreshedEvent. In Spring Boot you can also use ApplicationReadyEvent. Both fire after all singletons are initialized.
Initialization order between beans
If bean A depends on bean B, Spring fully initializes B first. That includes B's @PostConstruct. Dependencies therefore see an initialized collaborator. For beans with no declared dependency on each other, don't assume an order. Use @DependsOn("otherBean") when one needs another to be ready first without holding a reference to it.
Destruction runs in reverse dependency order
Spring destroys A before B when A depends on B. A can therefore still use B inside its own @PreDestroy.
Hooking into every bean
A BeanPostProcessor runs for every bean in the context. Spring's own features, such as @PostConstruct handling and AOP proxies, are built this way. Application code rarely needs one. When you write one, declare its @Bean method static so the processor is created early and doesn't force its configuration class to initialize too soon.
Choosing a mechanism
- Use
@PostConstructand@PreDestroyfor your own classes. - Use
initMethodanddestroyMethodin@Beanfor library classes. - Use
InitializingBeanandDisposableBeanonly when you are writing framework-style code that already depends on Spring. - Use context events for work that must happen after the whole application is assembled.
- Use
SmartLifecyclewhen a component needs ordered start and stop phases, such as a message listener that should start last and stop first.
Exercise
A singleton bean opens a file in a @PostConstruct method and closes it in a @PreDestroy method. A teammate changes the bean to @Scope("prototype"). What happens to the file handles, and how would you fix it?
Show answer
@PostConstruct still runs for each new instance, so every instance opens a file. Spring never calls @PreDestroy on prototype beans, so the files are never closed by the container. The fix is for the code that requests the prototype to close it itself, for example by making the bean AutoCloseable and using try-with-resources. Alternatively, keep the bean a singleton and make the file handle a per-call resource.
Exercise
A bean's @PostConstruct method calls its own method annotated with @Transactional, and no transaction is created. Why, and what is a better place for this call?
Show answer
Transactional proxies are created by a BeanPostProcessor after the initialization callbacks, so no proxy exists yet while @PostConstruct runs. A call on this also bypasses any proxy. Move the work to a listener for ContextRefreshedEvent or ApplicationReadyEvent, and call a method on an injected, proxied bean.