Spring bean lifecycle: from constructor to destroy
Spring creates every bean in a fixed sequence of steps, and it gives you several places to run your own code along the way. This page traces that sequence on a real context, then shows what happens when an init method fails, which beans are never destroyed, the order beans shut down in, and the traps that make a callback silently not run.
Contents
What the bean lifecycle is Every callback, traced in order @PostConstruct and @PreDestroy @Bean init and destroy methods, and inferred close() Prototype beans are never destroyed Startup and shutdown order, and SmartLifecycle Callbacks that silently do not run Other things to know Choosing a callback
What the bean lifecycle is
A Spring bean is an object whose creation and destruction the container controls. You never call new
For a singleton bean, the default, the sequence runs like this:
- Instantiation: the container calls the constructor (or the
factory method). Constructor arguments are the first dependencies injected.@Bean - Property population:
fields and setter methods are filled in.@Autowired - Aware callbacks: if the bean implements
,BeanNameAware orBeanFactoryAware , it receives its name, the bean factory or the context.ApplicationContextAware - Before-initialization post-processing: every
sees the bean throughBeanPostProcessor .postProcessBeforeInitialization - Initialization:
methods, then@PostConstruct , then a custom init method.InitializingBean.afterPropertiesSet() - After-initialization post-processing:
runs. This is where Spring wraps the bean in a proxy forpostProcessAfterInitialization ,@Transactional or other aspects, so the object other beans receive may be a proxy, not your class.@Async - In use: the bean serves the application until the context closes.
- Destruction:
methods, then@PreDestroy , then a custom destroy method.DisposableBean.destroy()
All of this happens inside refresh()new AnnotationConfigApplicationContext(Config.class)close()
| Mechanism | Defined by | Runs | Best for |
|---|---|---|---|
@PostConstruct@PreDestroy | Jakarta Annotations (jakarta.annotation | Init and destroy, first in each group | Classes you write; the usual choice |
InitializingBeanDisposableBean | Spring (org.springframework.beans.factory | Init and destroy, second | Framework code that should not depend on annotation processing |
@Bean(initMethod, destroyMethod) | Spring Java configuration | Init and destroy, third | Third-party classes you cannot annotate |
| Inferred destroy method | Spring, for @Bean | Destroy, when no destroy method is named | Anything with a public close()shutdown() |
BeanPostProcessor | Spring | Around the init callbacks of every bean | Cross-cutting changes to many beans, such as proxies |
SmartLifecycle | Spring | start()stop() | Background work: consumers, schedulers, servers |
SmartInitializingSingleton | Spring, since 4.1 | Once, after all singletons are created | Work that needs every other bean ready |
Every example on this page is a complete program on Spring Framework 7.0 without Spring Boot. Boot uses the same container, so the callbacks run identically there.
Every callback, traced in order
This program gives one bean every init and destroy mechanism at once, plus a BeanPostProcessor
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class LifecycleTrace {
static int step = 0;
static void log(String message) {
System.out.printf("%2d. %s%n", ++step, message);
}
@Configuration
static class Config {
@Bean
static BeanPostProcessor tracer() {
return new BeanPostProcessor() {
@Override
public Object postProcessBeforeInitialization(Object bean, String name) {
if (bean instanceof PriceCache) {
log("BeanPostProcessor.postProcessBeforeInitialization");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String name) {
if (bean instanceof PriceCache) {
log("BeanPostProcessor.postProcessAfterInitialization");
}
return bean;
}
};
}
@Bean
PriceFeed priceFeed() {
return new PriceFeed();
}
@Bean(initMethod = "customInit", destroyMethod = "customDestroy")
PriceCache priceCache() {
return new PriceCache();
}
}
static class PriceFeed {
}
static class PriceCache implements BeanNameAware, ApplicationContextAware,
InitializingBean, DisposableBean {
PriceCache() {
log("constructor");
}
@Autowired
void setFeed(PriceFeed feed) {
log("@Autowired setter: feed injected");
}
@Override
public void setBeanName(String name) {
log("BeanNameAware.setBeanName(\"" + name + "\")");
}
@Override
public void setApplicationContext(ApplicationContext context) {
log("ApplicationContextAware.setApplicationContext");
}
@PostConstruct
void postConstruct() {
log("@PostConstruct");
}
@Override
public void afterPropertiesSet() {
log("InitializingBean.afterPropertiesSet");
}
void customInit() {
log("@Bean(initMethod) customInit");
}
@PreDestroy
void preDestroy() {
log("@PreDestroy");
}
@Override
public void destroy() {
log("DisposableBean.destroy");
}
void customDestroy() {
log("@Bean(destroyMethod) customDestroy");
}
}
public static void main(String[] args) {
System.out.println("Starting the context:");
var context = new AnnotationConfigApplicationContext(Config.class);
log("context ready, bean in use: " + context.getBean(PriceCache.class).getClass()
.getSimpleName());
System.out.println("Closing the context:");
context.close();
}
}
Starting the context:
1. constructor
2. @Autowired setter: feed injected
3. BeanNameAware.setBeanName("priceCache")
4. ApplicationContextAware.setApplicationContext
5. BeanPostProcessor.postProcessBeforeInitialization
6. @PostConstruct
7. InitializingBean.afterPropertiesSet
8. @Bean(initMethod) customInit
9. BeanPostProcessor.postProcessAfterInitialization
10. context ready, bean in use: PriceCache
Closing the context:
11. @PreDestroy
12. DisposableBean.destroy
13. @Bean(destroyMethod) customDestroy
- Step 1 is the constructor and step 2 the
setter. Dependencies that are not constructor arguments arrive only after the object exists, which is why a constructor cannot use them.@Autowired - Steps 3 and 4 are the Aware callbacks. The bean learns that its name is
, taken from thepriceCache method name.@Bean - Step 5 is the post-processor's before hook, and steps 6 to 8 are the three init mechanisms, in the documented order: annotation, interface, custom method.
is itself run by a post-processor,@PostConstruct . Spring registers its own internal post-processors at the end of the chain, so yours sees the bean first.CommonAnnotationBeanPostProcessor - Step 9, the after hook, is the last step before the bean is ready. A post-processor that returns a different object here, such as a proxy, replaces the bean for everyone who injects it.
- Steps 11 to 13 are the destroy callbacks, again annotation, interface, custom method. They run only because
callsmain .context.close()
Using all three mechanisms on one bean is for the demonstration only. Pick one per bean. If two mechanisms name the same method, for example initMethod = "afterPropertiesSet"
@PostConstruct and @PreDestroy
@PostConstruct@PreDestroyvoid
Init callbacks run while the context is starting, so an exception in one stops the startup. Here a connection pool starts first, then a rate table fails to load its file:
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class InitFailure {
@Configuration
static class Config {
@Bean
ConnectionPool connectionPool() {
return new ConnectionPool();
}
@Bean
RateTable rateTable(ConnectionPool pool) {
return new RateTable();
}
}
static class ConnectionPool {
@PostConstruct
void open() {
System.out.println("ConnectionPool: opened 5 connections");
}
@PreDestroy
void close() {
System.out.println("ConnectionPool: closed 5 connections");
}
}
static class RateTable {
@PostConstruct
void load() {
System.out.println("RateTable: loading rates.csv");
throw new IllegalStateException("rates.csv not found");
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
System.out.println("never printed: " + context.getBeanDefinitionCount());
} catch (BeanCreationException e) {
System.out.println("Startup failed with " + e.getClass().getSimpleName());
System.out.println(" bean : " + e.getBeanName());
System.out.println(" message: " + e.getMessage());
System.out.println(" cause : " + e.getMostSpecificCause());
}
}
}
ConnectionPool: opened 5 connections
RateTable: loading rates.csv
ConnectionPool: closed 5 connections
Startup failed with BeanCreationException
bean : rateTable
message: Error creating bean with name 'rateTable': Invocation of init method failed
cause : java.lang.IllegalStateException: rates.csv not found
WARNING:Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'rateTable': Invocation of init method failed
opened first, becauseConnectionPool depends on it.rateTable threw, and the context constructor threwRateTable.load() instead of returning. Its message names the bean,BeanCreationException , and says an init method failed;rateTable returns the originalgetMostSpecificCause() .IllegalStateException- Before giving up, Spring destroyed the singletons it had already created, so the pool printed
. A failed startup does not leak resources that were set up with proper destroy callbacks.closed 5 connections - The
line at the end is Spring's own log record of the cancelled refresh. It goes to standard error, so it appears after the standard output here.WARNING
The annotations come from the jakarta.annotation-apijavax.annotationjakarta.annotationjakarta
@Bean init and destroy methods, and inferred close()
For a class you cannot change, such as a client from a library, name its methods on the @Bean@Bean(initMethod = "start", destroyMethod = "stop")close
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class DestroyInference {
static class FileArchive {
public void close() {
System.out.println(" FileArchive.close()");
}
}
static class MetricsReporter {
public void shutdown() {
System.out.println(" MetricsReporter.shutdown()");
}
}
static class SharedClient implements AutoCloseable {
@Override
public void close() {
System.out.println(" SharedClient.close()");
}
}
static class ScannedResource implements AutoCloseable {
@Override
public void close() {
System.out.println(" ScannedResource.close()");
}
}
static class PlainComponent {
public void close() {
System.out.println(" PlainComponent.close()");
}
}
@Configuration
static class Config {
@Bean // no destroyMethod given: Spring infers close()
FileArchive fileArchive() {
return new FileArchive();
}
@Bean // no close(), so Spring infers shutdown()
MetricsReporter metricsReporter() {
return new MetricsReporter();
}
@Bean(destroyMethod = "") // inference switched off
SharedClient sharedClient() {
return new SharedClient();
}
}
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext();
context.register(Config.class, ScannedResource.class, PlainComponent.class);
context.refresh();
System.out.println("Closing the context:");
context.close();
}
}
Closing the context:
MetricsReporter.shutdown()
FileArchive.close()
ScannedResource.close()
has a publicFileArchive and implements no interface, yet Spring called it. Forclose() methods the default@Bean is the special valuedestroyMethod , which looks for a public"(inferred)" orclose() .shutdown() has noMetricsReporter , so Spring fell back toclose() .shutdown() implementsSharedClient , butAutoCloseable turned inference off, and nothing was printed for it. Use this for an object whose life is managed elsewhere, such as a client that another library also holds.destroyMethod = "" was registered as a component class, not through aScannedResource method. Spring still called its@Bean , because it implementsclose() .AutoCloseable has a publicPlainComponent too, but it is a component class with no interface, and inference applies only toclose() methods. It was not closed.@Bean
The beans were destroyed in the reverse order of their creation. ScannedResource
Prototype beans are never destroyed
A prototype bean is created fresh for every request, and the container hands it over and forgets it. It still gets its init callbacks, but the container keeps no reference to call destroy callbacks later. This program asks for three report writers, destroys one by hand, then closes the context:
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
public class PrototypeDestroy {
static int created = 0;
@Component
@Scope("prototype")
static class ReportWriter {
private final int id = ++created;
@PostConstruct
void open() {
System.out.println(" @PostConstruct on writer " + id);
}
@PreDestroy
void close() {
System.out.println(" @PreDestroy on writer " + id);
}
}
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(ReportWriter.class);
System.out.println("Asking for three writers:");
ReportWriter first = context.getBean(ReportWriter.class);
context.getBean(ReportWriter.class);
context.getBean(ReportWriter.class);
System.out.println("Destroying writer 1 by hand:");
context.getBeanFactory().destroyBean(first);
System.out.println("Closing the context:");
context.close();
System.out.println("Context closed");
}
}
Asking for three writers:
@PostConstruct on writer 1
@PostConstruct on writer 2
@PostConstruct on writer 3
Destroying writer 1 by hand:
@PreDestroy on writer 1
Closing the context:
Context closed
- Each
call created a new writer, and each one rangetBean : writers 1, 2 and 3.@PostConstruct ran the destroy callbacks for writer 1. That is the way to clean up a prototype when you know you are done with it.getBeanFactory().destroyBean(first)- Closing the context printed nothing. Writers 2 and 3 never had
called. If they had held a file handle or a thread, it would have leaked.@PreDestroy
Give prototype beans nothing that needs closing, or have the code that asks for them close them, for example by making the bean AutoCloseable
Startup and shutdown order, and SmartLifecycle
Spring creates beans in dependency order and destroys them in the reverse order, so a bean can always use its dependencies in its own destroy callback. Some beans need a further step: a message consumer should start polling only once everything is ready, and stop polling before the database goes away. SmartLifecyclestart()stop()
import jakarta.annotation.PreDestroy;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
public class ShutdownOrder {
static class Database {
Database() {
System.out.println(" create Database");
}
@PreDestroy
void close() {
System.out.println(" destroy Database");
}
}
static class OrderRepository {
OrderRepository(Database db) {
System.out.println(" create OrderRepository");
}
@PreDestroy
void close() {
System.out.println(" destroy OrderRepository");
}
}
static class QueueConsumer implements SmartLifecycle {
private boolean running;
QueueConsumer(OrderRepository repository) {
System.out.println(" create QueueConsumer");
}
@Override
public void start() {
running = true;
System.out.println(" start QueueConsumer (polling the queue)");
}
@Override
public void stop() {
running = false;
System.out.println(" stop QueueConsumer (no new messages taken)");
}
@Override
public boolean isRunning() {
return running;
}
@PreDestroy
void close() {
System.out.println(" destroy QueueConsumer");
}
}
@Configuration
static class Config {
@Bean
QueueConsumer queueConsumer(OrderRepository repository) {
return new QueueConsumer(repository);
}
@Bean
OrderRepository orderRepository(Database db) {
return new OrderRepository(db);
}
@Bean
Database database() {
return new Database();
}
@EventListener
void onRefresh(ContextRefreshedEvent event) {
System.out.println(" event ContextRefreshedEvent");
}
@EventListener
void onClose(ContextClosedEvent event) {
System.out.println(" event ContextClosedEvent");
}
}
public static void main(String[] args) {
System.out.println("refresh():");
var context = new AnnotationConfigApplicationContext(Config.class);
System.out.println("close():");
context.close();
}
}
refresh():
create Database
create OrderRepository
create QueueConsumer
start QueueConsumer (polling the queue)
event ContextRefreshedEvent
close():
event ContextClosedEvent
stop QueueConsumer (no new messages taken)
destroy QueueConsumer
destroy OrderRepository
destroy Database
is declared first, butQueueConsumer was created first andDatabase second. Spring follows the dependencies, not the order of theOrderRepository methods.@Bean ran after all three beans existed, and beforestart() was published. AContextRefreshedEvent bean starts automatically duringSmartLifecycle , because itsrefresh() returnsisAutoStartup() by default.true- On
, theclose() came first, thenContextClosedEvent , and only then the destroy callbacks. The consumer stopped taking messages while the repository and database were still alive.stop() - The destroy callbacks ran in the reverse of the creation order: consumer, repository, database.
With several SmartLifecyclegetPhase()SmartLifecycle.DEFAULT_PHASEInteger.MAX_VALUELifecycleDefaultLifecycleProcessor
Destroy callbacks run only when something calls close()context.registerShutdownHook()
Callbacks that silently do not run
The worst lifecycle bugs produce no error: the callback simply does not happen, or happens without what you expected. This program shows three of them in one context:
import jakarta.annotation.PostConstruct;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;
public class LifecycleTraps {
static class Clock {
}
static class FieldInjected {
@Autowired
private Clock clock;
FieldInjected() {
System.out.println(" in the constructor : clock = " + clock);
}
@PostConstruct
void init() {
System.out.println(" in @PostConstruct : clock = "
+ clock.getClass().getSimpleName());
}
}
static class LegacyAnnotations {
// Both annotations are written out in full, so the two packages are easy to tell apart
@javax.annotation.PostConstruct
void javaxInit() {
System.out.println(" javax.annotation.PostConstruct ran");
}
@jakarta.annotation.PostConstruct
void jakartaInit() {
System.out.println(" jakarta.annotation.PostConstruct ran");
}
}
static class CacheLoader {
@PostConstruct
void init() {
System.out.print(" this.load() from @PostConstruct : ");
load();
}
@Transactional(readOnly = true)
public void load() {
System.out.println("transaction active = "
+ TransactionSynchronizationManager.isActualTransactionActive());
}
}
@Configuration
@EnableTransactionManagement
static class Config {
@Bean
DataSource dataSource() {
return new DriverManagerDataSource("jdbc:h2:mem:traps");
}
@Bean
PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
Clock clock() {
return new Clock();
}
@Bean
FieldInjected fieldInjected() {
return new FieldInjected();
}
@Bean
LegacyAnnotations legacyAnnotations() {
return new LegacyAnnotations();
}
@Bean
CacheLoader cacheLoader() {
return new CacheLoader();
}
@EventListener
void onRefresh(ContextRefreshedEvent event) {
System.out.print(" proxy.load() from ContextRefreshedEvent: ");
event.getApplicationContext().getBean(CacheLoader.class).load();
}
}
public static void main(String[] args) {
System.out.println("Starting the context:");
var context = new AnnotationConfigApplicationContext(Config.class);
System.out.println("Context started, active = " + context.isActive());
context.close();
}
}
Starting the context:
in the constructor : clock = null
in @PostConstruct : clock = Clock
jakarta.annotation.PostConstruct ran
this.load() from @PostConstruct : transaction active = false
proxy.load() from ContextRefreshedEvent: transaction active = true
Context started, active = true
- Field injection in the constructor: the constructor of
sawFieldInjected , because Spring fillsclock = null fields only after the object exists. In@Autowired the field was set. Use constructor injection, or move the code into@PostConstruct .@PostConstruct - The javax annotation:
has two init methods, and onlyLegacyAnnotations . The method marked withjakarta.annotation.PostConstruct ran compiled, because an oldjavax.annotation.PostConstruct annotation jar was on the classpath, and Spring Framework 7 ignored it without a warning. Search forjavax when you upgrade.javax.annotation - Transactions in @PostConstruct:
fromthis.load() ran with@PostConstruct , althoughtransaction active = false isload() . The call went to the object itself, not to the proxy, which is created only after the init callbacks. Called through the proxy from a@Transactional listener, the same method had a transaction.ContextRefreshedEvent
The general rule: @PostConstructApplicationListenerContextRefreshedEventSmartInitializingSingletonSmartLifecycleApplicationRunnerthis
Other things to know
- Lazy beans: a bean marked
is created, and its@Lazy run, on first use instead of during startup. That makes startup faster but moves init failures to the first request.@PostConstruct - Long init work: a slow
, such as loading a large cache, delays startup for the whole application, because by default singletons are created one at a time on the startup thread. Spring Framework 6.2 added@PostConstruct to create chosen beans on a background thread; without an@Bean(bootstrap = Bean.Bootstrap.BACKGROUND) bean namedExecutor , Spring logs a message and creates them on the startup thread anyway.bootstrapExecutor - BeanPostProcessor beans: declare
methods that return a@Bean asBeanPostProcessor , as the trace program does. Post-processors are created before other beans, and a non-static method forces its whole configuration class to be created early.static - Exceptions in destroy callbacks: Spring logs an exception thrown from a destroy method and continues with the next bean, so one failing
does not stop the others.close() - Checked exceptions: init and destroy methods may declare
. Spring wraps a failure inthrows Exception at startup.BeanCreationException
Choosing a callback
| You need to | Use |
|---|---|
| Check or prepare a bean you wrote, once it is injected | @PostConstruct |
| Release resources of a bean you wrote | @PreDestroyAutoCloseable |
| Start or stop a library class you cannot annotate | @Bean(initMethod = ..., destroyMethod = ...) |
| Keep Spring from closing a shared object | @Bean(destroyMethod = "") |
| Run background work only while the whole application is up | SmartLifecycle |
| Call transactional or other proxied methods at startup | A ContextRefreshedEventApplicationRunner |
| Change or wrap many beans as they are created | A staticBeanPostProcessor |
| Clean up a prototype bean | Close it yourself, or call destroyBean |
Keep each bean to one init and one destroy mechanism, prefer constructor injection so the object is complete when it is built, and make sure something calls close()@Bean