Sub topic 10
Bean lifecycle: initialization and destruction callbacks
This chapter assumes you know what a bean is, how the ApplicationContext creates singleton beans, and how constructor injection works. It covers the hooks Spring gives you to run code after a bean is ready and before it is thrown away.
The lifecycle in order
For a singleton bean, the container goes through these steps when the context starts and stops:
- Spring instantiates the bean by calling its constructor or factory method.
- Spring injects dependencies (constructor arguments are already in place, setters and fields come next).
- Spring runs the initialization callbacks.
- The bean is ready and stays in the container.
- When the context closes, Spring runs the destruction callbacks.
Initialization with @PostConstruct
A constructor runs before field and setter injection, so it cannot rely on those dependencies. A method annotated with @PostConstruct runs after all injection is done. Use it for work that needs a fully wired bean, such as loading a cache.
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;
@Component
public class PriceCache {
@PostConstruct
void warmUp() {
// runs once after dependencies are injected
}
@PreDestroy
void flush() {
// runs when the context closes
}
}In Spring 6 and Spring Boot 3 these annotations live in jakarta.annotation. Older versions used javax.annotation. If the import does not compile, check which Spring version you use.
Destruction with @PreDestroy
A method annotated with @PreDestroy runs when the context closes. Use it to release resources: flush buffers, close connections, stop threads. The callback only runs if the context is actually closed. In a plain main method, use try-with-resources as shown below. Spring Boot registers a shutdown hook for you.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
NotificationService service = ctx.getBean(NotificationService.class);
service.welcome("ana");
} // close() runs here, so @PreDestroy methods run
}
}Callbacks on @Bean methods
You cannot add annotations to a class you do not own. For beans defined in Java configuration, name the methods in @Bean instead.
@Bean(initMethod = "start", destroyMethod = "stop")
public ConnectionPool pool() {
return new ConnectionPool();
}Here ConnectionPool is your own class with start() and stop() methods. For @Bean methods, Spring also infers a public close() or shutdown() method as the destroy method automatically.
Scope changes the rules
Lifecycle callbacks depend on the scope:
| Scope | Initialization callback | Destruction callback |
|---|---|---|
| singleton | Runs once, at context startup | Runs when the context closes |
| prototype | Runs on every request to the container | Never runs. Spring does not track prototypes after handing them out |
If a prototype holds a resource, the code that asked for it must release it.
Common mistakes
- Putting dependency-dependent work in the constructor with field injection. The fields are still
nullthere. Use constructor injection or@PostConstruct. - Expecting
@PreDestroyto run when the JVM is killed abruptly. Akill -9skips it. - Throwing an exception from
@PostConstruct. The bean fails to initialize and the context fails to start. This is useful for failing fast, but keep it deliberate. - Doing slow work in
@PostConstructon many beans. Startup time grows with each one.
Exercise
A prototype-scoped bean has a method annotated with @PreDestroy. You close the context, but the method never runs. Why, and who must clean up?
Show answer
Spring creates a prototype bean, hands it to the caller, and then stops tracking it, so it never calls the destruction callback. The code that requested the bean must release its resources itself.
Exercise
Why would you put cache-loading code in a @PostConstruct method instead of the constructor when using field injection?
Show answer
With field injection, the fields are set after the constructor finishes, so they are still null in the constructor. @PostConstruct runs after injection, so the dependencies are available.