Sub topic 4
The phases of a bean's life
This chapter assumes you know core Java, basic Spring dependency injection (@Component, @Autowired, @Configuration, @Bean), and how to run a Spring application. It gives the map of a bean's life. Later chapters cover each callback and the full ordering in detail.
Two kinds of work: definitions and instances
The container does not start by creating objects. It starts by reading descriptions of objects. A bean definition is a recipe: the class to instantiate (or the factory method to call), the scope, the dependencies, the lazy flag, and the names of any init and destroy methods. The container turns your @Component classes and @Bean methods into these recipes first. It builds instances from them afterward.
This split explains most lifecycle behavior. The recipes can be changed before any instance exists, and instances are created according to the final recipes.
The phases in order
A singleton bean, the default scope, passes through these phases.
| Phase | What happens | Typical hook |
|---|---|---|
| 1. Definition loading | Component scanning, `@Configuration` parsing and `@Bean` methods register bean definitions. | `BeanFactoryPostProcessor` |
| 2. Definition post-processing | Registered post-processors may edit definitions, for example to resolve `${...}` placeholders. | `BeanFactoryPostProcessor` |
| 3. Instantiation | The container calls the constructor or factory method. | Constructor |
| 4. Population | Setter and field injection fill in dependencies. | `@Autowired` setters and fields |
| 5. Awareness | The bean learns its name, factory or context. | `BeanNameAware`, `ApplicationContextAware` |
| 6. Pre-initialization | Every `BeanPostProcessor` runs its "before" method. | `postProcessBeforeInitialization` |
| 7. Initialization | The bean's own init callbacks run. | `@PostConstruct`, `afterPropertiesSet`, `initMethod` |
| 8. Post-initialization | Every `BeanPostProcessor` runs its "after" method. It may replace the bean with a proxy. | `postProcessAfterInitialization` |
| 9. In use | The bean serves callers until the context closes. | None |
| 10. Destruction | The context closes and calls destruction callbacks on singletons. | `@PreDestroy`, `destroy`, `destroyMethod` |
Phases 3 to 8 are called creation. Phase 7 is the only one where the bean is fully injected but not yet visible to the rest of the application.
When each phase runs for a singleton
An ApplicationContext runs these phases as part of its refresh() step, which happens when you construct an AnnotationConfigApplicationContext or when Spring Boot starts. The sequence inside refresh() matters:
- The container loads all bean definitions.
- It runs the
BeanFactoryPostProcessorbeans, which can still change definitions. - It registers the
BeanPostProcessorbeans. These are created before ordinary beans, because they must be ready to process everything created after them. - It instantiates all non-lazy singletons, running phases 3 to 8 for each.
- It publishes a "context refreshed" event.
So by default, singleton beans are created at startup, not on first use. A broken constructor or a missing dependency fails the application at startup. The chapter on eager and lazy initialization covers how to change this.
Watching the phases run
The following program is complete. It needs spring-context (Spring Framework 6 or later) and jakarta.annotation-api on the classpath. On Spring 5, import javax.annotation instead of jakarta.annotation.
package demo;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Configuration
@ComponentScan
class AppConfig {
}
@Component
class Greeter {
String greeting() {
return "hello";
}
}
@Component
class Phased {
private Greeter greeter;
Phased() {
System.out.println("instantiation: constructor, greeter = " + greeter);
}
@Autowired
void setGreeter(Greeter greeter) {
this.greeter = greeter;
System.out.println("population: setter injection");
}
@PostConstruct
void init() {
System.out.println("initialization: greeter says " + greeter.greeting());
}
@PreDestroy
void cleanUp() {
System.out.println("destruction: @PreDestroy");
}
}
public class Main {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(AppConfig.class)) {
System.out.println("context running");
}
}
}The output is:
instantiation: constructor, greeter = null
population: setter injection
initialization: greeter says hello
context running
destruction: @PreDestroyThree things to notice:
- Nobody calls
getBean, yetPhasedis created. That is eager singleton creation duringrefresh(). - The constructor sees
greeterasnull. With setter or field injection, dependencies arrive after instantiation. This is why code that needs injected values belongs in an init callback, not in the constructor. @PreDestroyruns when thetryblock closes the context. If you never close the context, destruction callbacks never run (see the callout below).
Constructor injection changes phase 4
With constructor injection, the container must resolve dependencies before it can call the constructor. The population phase collapses into instantiation. The container fully creates and initializes each dependency first, so the dependency graph is built bottom-up. In the constructor you can safely use the arguments, though not any field the container injects later, such as @Autowired fields.
Circular dependencies are the edge case. If A needs B in its constructor and B needs A in its constructor, neither can be created first, and the container fails with BeanCurrentlyInCreationException. Setter and field cycles used to work because Spring exposed a half-built singleton early. Spring Boot 2.6 and later turn that off by default. Treat a cycle as a design problem and break it.
What the other beans see
Other beans never receive the bean created in phase 3 directly. They receive whatever phase 8 returns. A BeanPostProcessor may return a different object, usually a proxy that wraps the original. This is how @Transactional, @Async and @Cacheable work. Two consequences follow:
- The object passed to your
@PostConstructmethod is the raw bean. Calling a@Transactionalmethod onthisthere bypasses the transaction proxy, because the proxy does not exist yet. - Code that compares or casts injected beans by concrete class can fail if the injected object is a proxy. Depend on interfaces, or rely on class-based proxies.
Where scope changes the picture
The phases above describe a singleton. Scope changes the first and last phases:
- A singleton is created once during startup and destroyed when the context closes.
- A prototype bean goes through phases 3 to 8 each time it is requested. The container then hands it over and forgets it, so there is no destruction phase.
- Request, session and application scoped beans are created on demand when their scope begins, and destroyed when it ends.
Common errors
- Reading injected values in the constructor when using field or setter injection. They are still
null. - Doing slow or failing work in a constructor. It runs during
refresh()and aborts startup. Put it in an init callback only if you want that same effect, and be aware of it either way. - Expecting a
BeanPostProcessorbean to be post-processed by other post-processors. It is created early, so some features such as auto-proxying may not apply to it. Spring logs an info message when this happens. - Assuming a bean is created when first injected. Singletons are created at startup unless marked lazy.
Exercise
In the program above, change Phased so its constructor calls greeter.greeting() directly. What happens at startup, and which phase explains it?
Show answer
The application fails with a NullPointerException during context startup. The constructor runs in the instantiation phase, and the @Autowired setter runs in the later population phase, so greeter is still null. Moving the call into a @PostConstruct method fixes it. Alternatively, switch to constructor injection so the container passes the Greeter in before the constructor body runs.
Exercise
A singleton bean ReportService is annotated @Transactional on its generate() method. Its @PostConstruct method calls this.generate(). Why does the call run without a transaction?
Show answer
Transaction support is added by a BeanPostProcessor in the post-initialization phase, which wraps the bean in a proxy. @PostConstruct runs earlier, in the initialization phase, on the raw bean. The call on this therefore never passes through the proxy, and no transaction starts.