Skip to content
javahacks.dev
Spring Framework

Spring Bean Lifecycle From Definition to Destruction

Follow a Spring bean through definition, instantiation, injection, initialization callbacks, use and destruction, with the order of each hook shown in code.

6 min read
Summarize in AI
Flat illustration of a Spring container wiring beans together, with the Spring, Apache Maven, Spring Boot and JUnit5 logos.

A bean is more than the result of new. The container runs a fixed sequence around creation, and a surprising number of Spring features depend on one specific step in it. The sequence below is for Spring Framework 7, and the order has been stable across recent major versions. The fastest way to learn it is to watch it happen.

java
@Component
class Probe implements InitializingBean, DisposableBean, BeanNameAware {

    Probe()                              { log("1 constructor"); }
    @Autowired void setClock(Clock c)    { log("2 injection"); }
    public void setBeanName(String n)    { log("3 BeanNameAware"); }
    @PostConstruct void init()           { log("4 @PostConstruct"); }
    public void afterPropertiesSet()     { log("5 afterPropertiesSet"); }
    @PreDestroy void bye()               { log("6 @PreDestroy"); }
    public void destroy()                { log("7 destroy"); }

    private void log(String s)           { System.out.println(s); }
}

Start a context that contains Probe, then close it. A singleton prints:

Text
1 constructor
2 injection
3 BeanNameAware
4 @PostConstruct
5 afterPropertiesSet
6 @PreDestroy
7 destroy

Lines 1 to 5 appear during startup and lines 6 and 7 when the context closes. The numbers are in the strings, so you can add your own hooks to a bean and see where they land.

The phases, in order

  1. Definition. Scanning or a @Configuration class produces a BeanDefinition that records the class, scope and dependencies. A BeanFactoryPostProcessor can edit definitions at this point. This is how ${...} placeholders are resolved and how @Configuration classes are processed.
  2. Instantiation. The container calls the constructor, creating any constructor arguments first.
  3. Population. Fields and setters marked @Autowired or @Value are filled in.
  4. Aware callbacks. BeanNameAware, BeanFactoryAware and ApplicationContextAware hand the bean its container handles.
  5. Before initialization. Every BeanPostProcessor runs postProcessBeforeInitialization. A processor is what invokes @PostConstruct, so that annotation is not a language feature but a callback the container performs here.
  6. Initialization. InitializingBean.afterPropertiesSet runs, then a custom initMethod named in @Bean.
  7. After initialization. postProcessAfterInitialization runs on every processor. Proxies for @Transactional, @Async and @Cacheable are created here, and the object other beans receive may be a proxy wrapped around the one you constructed.
  8. In use. The bean serves calls.
  9. Destruction. On context close, @PreDestroy runs, then DisposableBean.destroy, then a custom destroyMethod.

Step 7 explains the most bugs

Proxies appear after initialization, so code inside @PostConstruct runs on the raw object. Put a @Transactional method behind a @PostConstruct call and the transaction is never opened:

java
@Service
class CatalogLoader {
    @Autowired CatalogRepository repository;

    @PostConstruct
    void load() {
        refresh();            // runs on 'this', not on the proxy
    }

    @Transactional
    void refresh() {
        repository.saveAll(readSeedData());
    }
}

refresh() executes without a transaction because no proxy exists yet, and the call goes through this regardless. The same mechanism, from a different angle, is self-invocation ignoring the proxy. Startup work that needs a transaction belongs in a listener that fires after the context is fully built:

java
@EventListener(ApplicationReadyEvent.class)
void load() {
    transactionTemplate.executeWithoutResult(status -> repository.saveAll(readSeedData()));
}

By the time that listener runs, every proxy is in place. TransactionTemplate also makes the boundary explicit, which is easier to read than relying on an annotation.

Writing your own step 5 and 7

The processors that Spring uses internally are public interfaces, and a small one is enough to see the mechanism:

java
@Component
class TimingPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String name) {
        if (bean instanceof Probe) System.out.println("before init: " + name);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String name) {
        if (bean instanceof Probe) System.out.println("after init: " + name);
        return bean;
    }
}

The value returned from postProcessAfterInitialization replaces the bean in the container. Returning a wrapper is how the proxying processors work. Returning null would be a bug, since it removes the bean from later processors. Define post-processors as static @Bean methods when they live in a configuration class, otherwise the configuration class has to be created too early and loses some of its own processing.

What the container does not manage

Prototype beans are created, populated and handed to the caller, and Spring never calls their destroy callbacks. The caller owns them from then on. Singletons are destroyed when the context closes, which a Spring Boot application triggers through a JVM shutdown hook. The container side of that, including what happens on a SIGTERM, is in handling signals.

Lazy singletons run the same sequence, just later: the first time something asks for them. That is why an error in a @Lazy bean can surface at the first request instead of at startup.

Choosing the callback

You needUse
Startup work that needs injected dependencies@PostConstruct
Releasing a resource on shutdown@PreDestroy, or implement AutoCloseable
Init and destroy on a third party class you cannot annotate@Bean(initMethod = "start", destroyMethod = "stop")
Work once the whole context is up, with proxiesApplicationReadyEvent or SmartInitializingSingleton
Ordered start and stop of long running componentsSmartLifecycle with a phase

@Bean methods infer a public no-argument close() or shutdown() method as the destroy method, so a DataSource or an ExecutorService is closed without any annotation. Set destroyMethod = "" when you do not want that, for a resource owned by someone else.

Lazy, scoped and conditional beans

The sequence above is for an eager singleton, which is created while the context starts. Three variations change when it happens. A @Lazy singleton runs the same steps the first time something asks for it, which moves errors in its construction from startup to the first request and delays the startup cost. A prototype bean runs the creation steps for every injection or lookup and never the destruction steps. A request-scoped or session-scoped bean is created per request or session, with destruction callbacks run when the scope ends, and the object injected elsewhere is a scoped proxy that looks up the current instance on each call.

Conditional beans, those guarded by @ConditionalOnProperty or a profile, do not enter the sequence at all when the condition is false: no definition is registered, so none of the callbacks run. If a lifecycle callback "does not fire", check whether the bean exists, using the beans endpoint or by printing the bean names, before you suspect the callback.

Ordering between beans

Creation order follows dependencies: a bean is created after the beans it needs. Between unrelated beans, the order is not something to rely on. When one bean must be initialised before another although there is no injected dependency, say so with @DependsOn("databaseMigrator"), which also reverses the order for destruction: dependents are destroyed first. For ordered start and stop of components that run threads or connections, implement SmartLifecycle and give it a phase, where lower phases start first and stop last.

java
@Component
class Poller implements SmartLifecycle {

    private volatile boolean running;

    public void start() { running = true; /* start the thread */ }
    public void stop()  { running = false; /* stop and join the thread */ }
    public boolean isRunning() { return running; }
    public int getPhase() { return 100; }
}

This is the right home for work that should begin only after the rest of the application is ready and end before the database pool closes.

Seeing the order in your own application

Turn on debug logging for org.springframework.beans.factory.support.DefaultListableBeanFactory to watch each singleton being created, and use the startup actuator endpoint, /actuator/startup, which records the time each step takes. A slow bean shows up as a long step, which is how to find the one that makes startup take twenty seconds. The related pitfalls for proxies are in the proxy guide.

Where this does not apply

Scopes other than singleton change what happens; see bean scopes. A failure at any step is reported as a BeanCreationException, and the cause chain tells you which step threw. The reference is the chapter on customizing the nature of a bean, the [BeanPostProcessor Javadoc](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/config/BeanPostProcessor.html) lists the hooks, and how the container works places the lifecycle in context.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.