A Spring bean has a lifecycle: the container creates it, injects its dependencies, runs its setup, hands it out for use, and runs its cleanup when the container closes. Knowing those steps tells you where your own setup and cleanup code belong. Code placed at the wrong step fails in quiet ways, so the order is worth learning once.
The five steps
A bean is an object the creates and manages. Each one goes through the same steps:
- the container calls the constructor;
- it injects the dependencies;
- it calls your init callback, the place for setup code;
- the bean is in use;
- when the container closes, it calls your destroy callback.
Setup belongs after injection
Our shop’s price cache loads prices from a price source at startup. In its first version, the source is injected into a field, and the constructor uses it:
@Autowired
private PriceSource source;
public BrokenPriceCache() {
System.out.println("constructor: source = " + source);
prices.putAll(source.load()); // source is still null here
}
Spring must create the object before it can set its fields. During the constructor, step 2 has not happened, so source is null and startup fails with a NullPointerException.
The first choice is constructor injection, where the dependency arrives as a parameter and is never null:
public ConstructorPriceCache(PriceSource source) {
System.out.println("constructor: source = " + source);
prices.putAll(source.load());
}
The other fix is a method marked @PostConstruct, which runs after every dependency is injected; see FixedPriceCache.java. Keep @PostConstruct for setup that needs the finished bean, and keep it short, because startup waits for it.
Three ways to hook in
Spring offers three hooks for setup: @PostConstruct, InitializingBean.afterPropertiesSet and an init method named on @Bean. It offers three matching hooks for cleanup. The Spring docs recommend @PostConstruct and @PreDestroy, because they do not tie your class to Spring. For @Bean methods, a public close method is called at shutdown on its own.
When beans are created
Singletons are created once, at startup, so a broken bean stops the app at once instead of hours later. For a slow, rarely used bean such as our sales report, that delays every start. One annotation changes the moment:
@Component
@Lazy
public class LazySalesReport {
The report is now created the first time someone asks for it. But a lazy bean with a problem only fails when first used, so use @Lazy sparingly.
Cleanup needs a closed container
The price export creates a temp folder at startup and deletes it in @PreDestroy. A small main that starts a container, uses the bean and ends leaves the folder behind, because destroy callbacks run only when the container closes. The fix is to close it:
try (var context = new AnnotationConfigApplicationContext(PriceExport.class)) {
System.out.println("working with " + context.getBean(PriceExport.class).getClass().getSimpleName());
}
With try-with-resources, the container closes at the end of the block, and the folder goes. Spring Boot registers a shutdown hook, so Ctrl+C or a normal stop signal also closes the context. A forced kill -9 ends the JVM at once, and no cleanup runs.
Creation order and @DependsOn
A dependency is always created before the bean that needs it, so the price source exists before the price cache. But the price source reads a table that the migrations bean creates, and it never calls the migrations, so Spring cannot see that link. Name it explicitly:
@Bean
@DependsOn("migrations")
public PriceSource priceSource() {
return new PriceSource();
}
Now the migrations run first, and the price source finds its table.
Shutdown runs in reverse: the cache closes first, then the price source, then the migrations. A bean is never destroyed while a bean that needs it is still running.
Recap
- A bean is constructed, injected, initialized, used, then destroyed when the container closes.
- Don’t do setup in a constructor that needs injected fields. Prefer constructor injection, and
@PostConstructfor work that needs the finished bean. @Lazydelays creation, so a broken lazy bean fails only when first used.- Destroy callbacks run only when the container closes. Spring Boot registers a shutdown hook, but
kill -9skips cleanup. @DependsOnstates a dependency Spring cannot see. Shutdown runs in reverse order.
Sources
Official documentation and well-known tutorials read while writing this article. The wording here is our own.
- Spring Framework reference: Using @PostConstruct and @PreDestroy
- Spring Framework reference: Customizing the Nature of a Bean
- Baeldung: Spring PostConstruct and PreDestroy Annotations
- HowToDoInJava: Spring Bean Life Cycle in Spring Boot: Phases and Order
- LogicBig: Receiving lifecycle callbacks by using @PostConstruct and @PreDestroy
Comments