Spring Bean Lifecycle
The Spring bean lifecycle is the sequence of steps the container follows for every bean: it creates the object, injects its dependencies, gives it a chance to initialize, possibly wraps it in a proxy, hands it out for use, and finally gives it a chance to clean up when the application stops. Knowing the exact order tells you where setup code is safe, why @Transactional does not work in some callbacks, and why a cleanup method sometimes never runs.
This tutorial walks through each phase in order, compares the three ways to write initialization and destruction callbacks, and runs a bean that logs every callback so you can see the real sequence. It then covers the special cases: prototype beans, inferred destroy methods, work that needs all beans to exist, and graceful shutdown.
1. What Is the Spring Bean Lifecycle?
A bean is an object created and managed by the Spring container. Unlike an object you create with new, a bean goes through extra steps that Spring controls. Those steps, from creation to destruction, are the bean lifecycle.
For a default singleton bean in Spring Boot, the lifecycle starts during the context refresh at startup and ends when the context closes at shutdown. In between, the same instance serves every caller. The startup side is explained in the application startup process.
2. The Bean Lifecycle Phases in Order
| # | Phase | What happens | Is the bean usable by others yet? |
|---|---|---|---|
| 1 | Instantiation | The constructor runs; constructor dependencies are passed in | No |
| 2 | Property population | Setter and field dependencies (@Autowired, @Value) are injected | No |
| 3 | Aware callbacks | BeanNameAware, BeanClassLoaderAware, BeanFactoryAware, then context-level ones such as EnvironmentAware and ApplicationContextAware | No |
| 4 | Before initialization | Each BeanPostProcessor's postProcessBeforeInitialization; @PostConstruct runs here | No |
| 5 | Initialization | InitializingBean.afterPropertiesSet(), then the custom init method | No |
| 6 | After initialization | Each postProcessAfterInitialization; proxies for transactions, caching and AOP are created here | The returned object (possibly a proxy) is what others get |
| 7 | In use | The bean serves calls until shutdown | Yes |
| 8 | Destruction | @PreDestroy, DisposableBean.destroy(), then the custom or inferred destroy method | No longer |
Phases 4 and 6 are where bean post-processors act. Their most important job is in phase 6: replacing your bean with a proxy that adds behavior. Everything before phase 6 sees the raw object, not the proxy.
3. Initialization Callbacks Compared
There are three ways to run code after dependencies are injected. If a bean uses more than one, they run in this order:
| Order | Mechanism | How | Couples the class to Spring? |
|---|---|---|---|
| 1 | @PostConstruct | Annotate a no-argument method (jakarta.annotation.PostConstruct) | No, it is a Jakarta standard annotation |
| 2 | InitializingBean | Implement afterPropertiesSet() | Yes |
| 3 | Custom init method | @Bean(initMethod = "start") | No, configured outside the class |
Use @PostConstruct for your own classes. Use initMethod for third-party classes you cannot annotate. InitializingBean is mostly used inside Spring itself.
4. Destruction Callbacks Compared
| Order | Mechanism | How |
|---|---|---|
| 1 | @PreDestroy | Annotate a no-argument method (jakarta.annotation.PreDestroy) |
| 2 | DisposableBean | Implement destroy() |
| 3 | Custom or inferred destroy method | @Bean(destroyMethod = "shutdown"), or automatically a public close() or shutdown() method |
Inferred destroy methods: for beans declared with @Bean, Spring calls a public no-argument close() or shutdown() method automatically, and beans implementing AutoCloseable are closed too. This is why a @Bean that returns a connection pool is closed at shutdown without any configuration. Set destroyMethod = "" to switch it off when the object is shared and must not be closed by Spring.
Beans are destroyed in the reverse order of their dependencies: a bean is destroyed before the beans it depends on, so a repository's connection pool is still open while the repository cleans up.
5. A Complete Example: Logging Every Lifecycle Step
This bean uses every callback, purely to show the order. In real code you would pick one initialization and one destruction mechanism.
5.1 The Bean
package com.javabytechie.shop.pricing;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class PriceFeed implements BeanNameAware, ApplicationContextAware, InitializingBean, DisposableBean {
private static final Logger log = LoggerFactory.getLogger(PriceFeed.class);
private final CurrencyRates rates;
private PriceFormatter formatter;
public PriceFeed(CurrencyRates rates) {
this.rates = rates;
log.info("1. constructor (rates injected: {})", rates != null);
}
@Autowired
void setFormatter(PriceFormatter formatter) {
this.formatter = formatter;
log.info("2. setter injection");
}
@Override
public void setBeanName(String name) {
log.info("3a. BeanNameAware: {}", name);
}
@Override
public void setApplicationContext(ApplicationContext context) {
log.info("3b. ApplicationContextAware");
}
@PostConstruct
void postConstruct() {
log.info("4. @PostConstruct");
}
@Override
public void afterPropertiesSet() {
log.info("5a. InitializingBean.afterPropertiesSet()");
}
void connect() {
log.info("5b. custom initMethod connect()");
}
public String price(String sku) {
return formatter.format(rates.convert(sku));
}
@PreDestroy
void preDestroy() {
log.info("8a. @PreDestroy");
}
@Override
public void destroy() {
log.info("8b. DisposableBean.destroy()");
}
void disconnect() {
log.info("8c. custom destroyMethod disconnect()");
}
}
5.2 Its Dependencies and Configuration
package com.javabytechie.shop.pricing;
import java.math.BigDecimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class PricingConfig {
private static final Logger log = LoggerFactory.getLogger(PricingConfig.class);
@Bean
CurrencyRates currencyRates() {
return new CurrencyRates();
}
@Bean
PriceFormatter priceFormatter() {
return new PriceFormatter();
}
@Bean(initMethod = "connect", destroyMethod = "disconnect")
PriceFeed priceFeed(CurrencyRates rates) {
return new PriceFeed(rates);
}
@Bean
ApplicationRunner priceDemo(PriceFeed feed) {
return args -> log.info("7. in use: KB-100 costs {}", feed.price("KB-100"));
}
}
class CurrencyRates {
BigDecimal convert(String sku) {
return new BigDecimal("79.99");
}
}
class PriceFormatter {
String format(BigDecimal amount) {
return "EUR " + amount;
}
}
5.3 Output
1. constructor (rates injected: true)
2. setter injection
3a. BeanNameAware: priceFeed
3b. ApplicationContextAware
4. @PostConstruct
5a. InitializingBean.afterPropertiesSet()
5b. custom initMethod connect()
Started ShopApplication in 1.21 seconds (process running for 1.48)
7. in use: KB-100 costs EUR 79.99
...
8a. @PreDestroy
8b. DisposableBean.destroy()
8c. custom destroyMethod disconnect()
Phase 6 is not logged because no post-processor wraps PriceFeed. If one of its methods were @Transactional, phase 6 is where the transaction proxy would replace it.
6. Running Code After All Singletons Exist
@PostConstruct runs when this bean is ready, but other beans may still be under construction. When you need the whole container, use one of these:
| Hook | Runs | Typical use |
|---|---|---|
SmartInitializingSingleton.afterSingletonsInstantiated() | Once, after all non-lazy singletons are created, still inside the refresh | Framework-style setup that inspects other beans |
SmartLifecycle.start() | At the end of the refresh, in phase order; stop() at shutdown | Starting and stopping background work such as consumers or pollers |
ApplicationRunner or ApplicationReadyEvent | After the context is fully started | Application tasks such as loading reference data |
7. Lifecycle of Prototype and Other Scoped Beans
- Prototype beans: Spring runs phases 1 to 6 for every new instance, then hands it over and forgets it. Destruction callbacks are never called; the code that asked for the bean must clean it up.
- Request and session beans: created at the first use within a request or session, and destroyed, with callbacks, when that request or session ends.
- Lazy singletons: the full lifecycle runs at the first use instead of at startup; see lazy initialization.
Scopes are covered in detail in Spring bean scopes.
8. Common Lifecycle Pitfalls
8.1 @Transactional in @PostConstruct Does Nothing
@PostConstruct runs in phase 4, on the raw object, before the transaction proxy exists in phase 6. Even later, a call through this never goes through the proxy. Move such work to an ApplicationRunner or an ApplicationReadyEvent listener that calls the bean through its proxy.
8.2 Heavy Work in Constructors
A constructor that opens network connections or loads large files slows down startup and fails before the bean is complete. Assign fields in the constructor; do the work in an initialization callback, or later.
8.3 @PreDestroy Not Called
Destruction callbacks run only when the context closes. Spring Boot registers a JVM shutdown hook, so they run on a normal stop or a SIGTERM from Kubernetes. They do not run after kill -9, a JVM crash or an out-of-memory kill, so never rely on them for data that must not be lost.
8.4 Using javax Annotations
Spring Framework 6 and later only recognize jakarta.annotation.PostConstruct and PreDestroy. An old javax.annotation.PostConstruct import compiles if the old library is on the classpath but is silently ignored.
9. Best Practices
- Keep constructors to field assignment and validation of arguments.
- Use
@PostConstructand@PreDestroyfor your own classes; useinitMethodanddestroyMethodfor third-party classes. - Choose one mechanism per phase instead of combining several on one bean.
- Do not call proxied methods from init callbacks; use a runner or the ready event.
- Clean up prototype beans yourself, or avoid prototypes that hold resources.
- Make shutdown work quick and safe to skip, because a killed process never runs it.
10. Summary
The Spring bean lifecycle runs in a fixed order: instantiate with constructor injection, populate setter and field dependencies, call Aware interfaces, run post-processors before initialization (including @PostConstruct), call afterPropertiesSet() and the custom init method, run post-processors after initialization, where proxies are created, and finally, at shutdown, call @PreDestroy, destroy() and the custom or inferred destroy method. Prototype beans never get destruction callbacks, and initialization callbacks always see the raw object, not the proxy. Put light setup in @PostConstruct, application-wide startup tasks in runners, and keep cleanup quick, and the lifecycle will work for you.
11. References
Spring Bean Lifecycle Interview Questions and Answers
Common interview questions on Spring Bean Lifecycle, from basic to scenario-based, with short answers you can explain in your own words.
Q. In what order are @PostConstruct, afterPropertiesSet() and a custom initMethod called?
Answer: @PostConstruct first, because it is run by CommonAnnotationBeanPostProcessor in the before-initialization step. Then InitializingBean.afterPropertiesSet(), then the custom init method. Destruction mirrors this: @PreDestroy, then DisposableBean.destroy(), then the custom or inferred destroy method. A bean should normally use only one mechanism per phase.
Q. Why does a @Transactional method called from @PostConstruct run without a transaction?
Answer: Transactions are applied by a proxy that a bean post-processor creates after initialization. @PostConstruct runs before that, on the raw object, and calls through this never pass through a proxy anyway. Move the work to an ApplicationRunner or an ApplicationReadyEvent listener that calls the bean, or use a TransactionTemplate inside the callback.
Q. Are destruction callbacks called for prototype beans?
Answer: No. The container fully initializes each prototype instance, hands it to the caller and does not keep a reference, so it never calls @PreDestroy or destroy methods on it. If a prototype holds resources, the caller must release them, for example by making it AutoCloseable and using try-with-resources. Request and session scoped beans, by contrast, are destroyed with callbacks when their scope ends.
Q. What is an inferred destroy method?
Answer: For beans declared with @Bean, the default destroyMethod is "inferred": Spring automatically calls a public no-argument close() or shutdown() method at shutdown, and closes AutoCloseable beans. That is how connection pools and clients from @Bean methods are closed without configuration. Set destroyMethod = "" to disable it for objects that Spring must not close.
Q. When would you use SmartInitializingSingleton instead of @PostConstruct?
Answer: When the setup needs all singletons to exist, for example a registry that collects every bean of a type or checks configuration across beans. afterSingletonsInstantiated() runs once after all non-lazy singletons are created, while @PostConstruct runs as soon as one bean is ready, when others may still be under construction. For application tasks, an ApplicationRunner is usually simpler.
Q. A service flushes buffered audit records in a @PreDestroy method, but records are lost after some restarts. Why, and how do you fix it?
Answer: @PreDestroy runs only when the context closes normally. A forced kill, a JVM crash or an out-of-memory kill skips it, and a slow flush can also be cut off by the shutdown timeout. Do not buffer records that must survive: write them synchronously, use a transactional outbox, or flush small batches frequently. Keep the shutdown flush only as a best-effort extra, and make sure Kubernetes sends SIGTERM with enough grace period.