Bean Lifecycle
A bean goes through several stages
When the container needs a bean, the work does not end with a constructor call. Spring creates the object, provides its dependencies, runs the initialization stage, and when the context closes, it can give the object a chance to release resources.
@Component
class CacheClient {
@PostConstruct
void connect() {
System.out.println("connected");
}
@PreDestroy
void disconnect() {
System.out.println("disconnected");
}
}
A method marked with @PostConstruct is called after
the object has been created and its dependencies have already been set. This is a suitable place for initialization
that needs ready dependencies. @PreDestroy lets the bean perform
cleanup before it is destroyed during a normal context shutdown.
A simplified sequence
- Spring creates a bean instance.
- The container provides the required dependencies.
- Spring mechanisms that work around initialization are applied.
- Initialization callbacks run.
- The bean is ready for normal work.
- When the context shuts down, destruction callbacks run.
Later, we will separately cover the mechanism that lets Spring participate in the stages before and after initialization. For now, the main idea is enough: a bean exists inside a lifecycle managed by the container.