Bean Lifecycle

Basic Spring
≈ 2 min read

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

  1. Spring creates a bean instance.
  2. The container provides the required dependencies.
  3. Spring mechanisms that work around initialization are applied.
  4. Initialization callbacks run.
  5. The bean is ready for normal work.
  6. 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.

The constructor is not yet the moment when a bean is fully ready. If initialization depends on other beans, it is safer to perform it after the container has finished injecting dependencies.