00:00

Spring Bean Lifecycle

Last updated:

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.

Analogy: Think of a new employee. They are hired (instantiated), given a laptop and accounts (dependencies), told the company's name and rules (Aware callbacks), go through onboarding (initialization), maybe get an assistant who handles their calendar (a proxy), then do their job. When they leave, they hand everything back (destruction).

2. The Bean Lifecycle Phases in Order

Spring bean lifecycle phasesCreation phases: the container instantiates the bean by calling its constructor with constructor dependencies, populates setter and field dependencies, calls Aware interfaces such as BeanNameAware and ApplicationContextAware, runs BeanPostProcessor before-initialization methods including @PostConstruct, then InitializingBean.afterPropertiesSet, then a custom init method, and finally BeanPostProcessor after-initialization methods, which may return a proxy. The bean is then in use. After all singletons exist, SmartInitializingSingleton callbacks run. At shutdown, @PreDestroy runs, then DisposableBean.destroy, then a custom destroy method. 1. Instantiate constructor + constructor injection 2. Populate setter and field injection 3. Aware callbacks bean name, factory, context, environment 4. Before init post-processors, incl. @PostConstruct 5. afterProperties- Set() then custom init method 6. After init post-processors may return a proxy (@Transactional, @Async, AOP) 7. Ready for use injected into other beans; SmartInitializingSingleton runs 8. Destroy (context close): @PreDestroy, then DisposableBean.destroy(), then custom or inferred destroy method
Creation runs left to right and top to bottom; destruction runs in reverse dependency order when the context closes.
#PhaseWhat happensIs the bean usable by others yet?
1InstantiationThe constructor runs; constructor dependencies are passed inNo
2Property populationSetter and field dependencies (@Autowired, @Value) are injectedNo
3Aware callbacksBeanNameAware, BeanClassLoaderAware, BeanFactoryAware, then context-level ones such as EnvironmentAware and ApplicationContextAwareNo
4Before initializationEach BeanPostProcessor's postProcessBeforeInitialization; @PostConstruct runs hereNo
5InitializationInitializingBean.afterPropertiesSet(), then the custom init methodNo
6After initializationEach postProcessAfterInitialization; proxies for transactions, caching and AOP are created hereThe returned object (possibly a proxy) is what others get
7In useThe bean serves calls until shutdownYes
8Destruction@PreDestroy, DisposableBean.destroy(), then the custom or inferred destroy methodNo 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:

OrderMechanismHowCouples the class to Spring?
1@PostConstructAnnotate a no-argument method (jakarta.annotation.PostConstruct)No, it is a Jakarta standard annotation
2InitializingBeanImplement afterPropertiesSet()Yes
3Custom 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

OrderMechanismHow
1@PreDestroyAnnotate a no-argument method (jakarta.annotation.PreDestroy)
2DisposableBeanImplement destroy()
3Custom 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

PriceFeed.java
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

PricingConfig.java
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

Console (startup, then Ctrl+C)
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:

HookRunsTypical use
SmartInitializingSingleton.afterSingletonsInstantiated()Once, after all non-lazy singletons are created, still inside the refreshFramework-style setup that inspects other beans
SmartLifecycle.start()At the end of the refresh, in phase order; stop() at shutdownStarting and stopping background work such as consumers or pollers
ApplicationRunner or ApplicationReadyEventAfter the context is fully startedApplication 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 @PostConstruct and @PreDestroy for your own classes; use initMethod and destroyMethod for 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