Bean lifecycle

Key idea
Spring creates every bean in a fixed order: first it adjusts the recipes (BeanFactoryPostProcessor), then it instantiates, injects, calls the Aware interfaces, passes the bean through the BeanPostProcessors before and after initializing it and, on shutdown, destroys it. Knowing what happens in each phase tells you where to put things.
In the box
The box door controller tried to open in its constructor, before it had a clock. Walk through the phases every bean goes through, from recipe to destruction, and the exact callback order the exam asks about.
ApplicationContextClockEagerDoor

EagerDoor, in red, receives the Clock too late: the too late packet arrives when the constructor has already failed.

LifecycleConfig sends a BeanDefinition to CapacityPostProcessor, both highlighted; DoorController isn't created yet.

DoorController, highlighted, receives capacity=20 from the post-processor and setClock() from the Clock, also highlighted.

LoggingBeanPostProcessor, highlighted, sends before / after to DoorController: it processes it before and after initialization.

DoorController, highlighted, runs its three init callbacks with all its dependencies already injected.

AuditingPostProcessor, highlighted, sends getProxy() to CheckInDesk (proxy): the context will keep the proxy instead of the original object.

CapacityPostProcessor, DoorController and LoggingBeanPostProcessor highlighted: the three pieces of the full order.

DoorController, highlighted, runs its three destruction callbacks when the context closes.

Final view of the staircase: LifecycleConfig, CapacityPostProcessor, DoorController with its Clock and LoggingBeanPostProcessor.

Step 1 of 9

Opening the door before having a clock

The box door controller (EagerDoor) has to record what time it opens. It gets the Clock through an @Autowired setter and, in its constructor, calls LocalTime.now(clock).

Result: NullPointerException at startup. When the constructor runs, Spring hasn't injected anything yet: the setter is called afterwards.

Step 2 of 9

Phase 0: recipes and the BeanFactoryPostProcessor

Before creating a single bean, Spring reads the configuration and builds a BeanDefinition per bean: the recipe (class, scope, dependencies, properties, init and destroy methods).

A BeanFactoryPostProcessor (BFPP) can modify the recipes at that point. CapacityPostProcessor changes the doorController definition so Spring sets capacity = 20.

The most famous BFPP is PropertySourcesPlaceholderConfigurer, the one that replaces ${…}.

Step 3 of 9

Phases 1 to 3: instantiate, inject, Aware

With the recipes ready, for each singleton:

  1. Instantiate: call the constructor (if it has parameters, those dependencies are resolved here).
  2. Inject the rest: @Autowired on setters and fields (setClock) and the definition's properties (setCapacity(20), set by the BFPP).
  3. Call the Aware interfaces it implements: BeanNameAware.setBeanName, BeanFactoryAware, ApplicationContextAware…

Step 4 of 9

Phases 4 and 8: the BeanPostProcessor

A BeanPostProcessor (BPP) receives every bean in the context at two moments:

  • postProcessBeforeInitialization: just before the init callbacks.
  • postProcessAfterInitialization: just after.

Both return an object: it can be the same bean or another one that replaces it.

Much of Spring is made of BPPs: @Autowired is processed by AutowiredAnnotationBeanPostProcessor and @PostConstruct by CommonAnnotationBeanPostProcessor. Our LoggingBeanPostProcessor is PriorityOrdered so it runs before the latter and the log shows the classic order.

Step 5 of 9

Phases 5 to 7: the init callbacks

Between "before" and "after" come the initialization methods, in this order:

  1. @PostConstruct (Jakarta annotation). This is where DoorController computes openedAt: the clock is there.
  2. InitializingBean.afterPropertiesSet() (Spring interface, couples your class to Spring).
  3. @Bean(initMethod = "openDoors") (handy for classes you can't annotate, like a library's).

Step 6 of 9

After initialization comes the proxy

postProcessAfterInitialization can return another object. AuditingPostProcessor does so for classes annotated with @Audited: it creates a proxy with ProxyFactory that records every call and returns the proxy.

From then on, the context keeps and hands out the proxy, not your CheckInDesk. The test checks it with AopUtils.isCglibProxy.

Step 7 of 9

The full order, verified

The test starts the context, closes it and compares the log with the exact list:

BFPP → constructor → injection → BeanNameAware → BPP before → @PostConstruct → afterPropertiesSet → initMethod → BPP after → (bean in use) → @PreDestroy → destroy() → destroyMethod.

Step 8 of 9

On shutdown: destruction

When close() is called (or the application stops), Spring destroys singletons in reverse dependency order:

  1. @PreDestroy.
  2. DisposableBean.destroy().
  3. @Bean(destroyMethod = "lockDoors").

Step 9 of 9

Recap

  • Recipes: BeanDefinition + BeanFactoryPostProcessor (static).
  • Construction: constructor → injection → Aware.
  • Initialization: BPP before → @PostConstruct → afterPropertiesSet → initMethod → BPP after (proxies appear here).
  • Destruction: @PreDestroy → destroy → destroyMethod (not for prototypes).

Cheatsheet →

Code

EagerDoor.java

/** Before: start-up work in the constructor, where setter-injected dependencies are still null. */
public class EagerDoor {
    private Clock clock;
    private LocalTime openedAt;

    public EagerDoor() {
        this.openedAt = LocalTime.now(clock); // NullPointerException: clock is not injected yet
    }

    @Autowired
    public void setClock(Clock clock) {
        this.clock = clock;
    }
}

CapacityPostProcessor.java

/** Runs once, before any regular bean exists, and edits the RECIPES (bean definitions), not beans. */
public class CapacityPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) {
        BeanDefinition door = factory.getBeanDefinition("doorController");
        door.getPropertyValues().add("capacity", 20); // Spring will call setCapacity(20)
        LifecycleLog.add("0 BeanFactoryPostProcessor");
    }
}

DoorController.java

public DoorController() {
    LifecycleLog.add("1 constructor");
}

@Autowired
public void setClock(Clock clock) {             // dependency injection
    this.clock = clock;
    LifecycleLog.add("2 inject clock");
}

public void setCapacity(int capacity) {         // value set by the BeanFactoryPostProcessor
    this.capacity = capacity;
    LifecycleLog.add("2 inject capacity=" + capacity);
}

@Override
public void setBeanName(String name) {          // Aware callbacks come after injection
    LifecycleLog.add("3 BeanNameAware " + name);
}

LoggingBeanPostProcessor.java

/** Called for EVERY bean, around its initialization callbacks. */
public class LoggingBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String name) {
        if (bean instanceof DoorController) LifecycleLog.add("4 BPP before init");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String name) {
        if (bean instanceof DoorController) LifecycleLog.add("8 BPP after init");
        return bean; // could return a different object, e.g. a proxy
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE; // before the processor that runs @PostConstruct
    }
}

DoorController.java

@PostConstruct
void postConstruct() {
    openedAt = LocalTime.now(clock);           // safe: every dependency is set
    LifecycleLog.add("5 @PostConstruct");
}

@Override
public void afterPropertiesSet() {
    LifecycleLog.add("6 afterPropertiesSet");
}

public void openDoors() {                       // @Bean(initMethod = "openDoors")
    open = true;
    LifecycleLog.add("7 initMethod");
}

AuditingPostProcessor.java

/** After initialization, swaps every @Audited bean for a proxy: how AOP and @Transactional get in. */
public class AuditingPostProcessor implements BeanPostProcessor {
    public static final List<String> AUDIT = new CopyOnWriteArrayList<>();

    @Override
    public Object postProcessAfterInitialization(Object bean, String name) {
        if (!bean.getClass().isAnnotationPresent(Audited.class)) {
            return bean;
        }
        ProxyFactory factory = new ProxyFactory(bean);
        factory.setProxyTargetClass(true);                        // subclass proxy (CGLIB)
        factory.addAdvice((MethodInterceptor) call -> {
            AUDIT.add(call.getMethod().getName());
            return call.proceed();
        });
        return factory.getProxy();                                // the context keeps THIS object
    }
}

LifecycleOrderTest.java

@Test
void theCallbacksRunInTheDocumentedOrder() {
    var ctx = new AnnotationConfigApplicationContext(LifecycleConfig.class);
    DoorController door = ctx.getBean(DoorController.class);
    assertThat(door.isOpen()).isTrue();
    assertThat(door.capacity()).isEqualTo(20);   // changed in the recipe by the BFPP

    ctx.close();
    assertThat(LifecycleLog.events()).containsExactly(
        "0 BeanFactoryPostProcessor",
        "1 constructor",
        "2 inject clock", "2 inject capacity=20",
        "3 BeanNameAware doorController",
        "4 BPP before init",
        "5 @PostConstruct", "6 afterPropertiesSet", "7 initMethod",
        "8 BPP after init",
        "10 @PreDestroy", "11 DisposableBean.destroy", "12 destroyMethod");
}

DoorController.java

@PreDestroy
void preDestroy() {
    LifecycleLog.add("10 @PreDestroy");
}

@Override
public void destroy() {
    LifecycleLog.add("11 DisposableBean.destroy");
}

public void lockDoors() {                       // @Bean(destroyMethod = "lockDoors")
    open = false;
    LifecycleLog.add("12 destroyMethod");
}

LifecycleConfig.java

@Configuration
public class LifecycleConfig {

    @Bean // static: post-processors are created before every other bean
    public static CapacityPostProcessor capacityPostProcessor() {
        return new CapacityPostProcessor();
    }

    @Bean
    public static LoggingBeanPostProcessor loggingBeanPostProcessor() {
        return new LoggingBeanPostProcessor();
    }

    @Bean
    public static AuditingPostProcessor auditingPostProcessor() {
        return new AuditingPostProcessor();
    }

    @Bean
    public Clock clock() {
        return Clock.systemUTC();
    }

    @Bean(initMethod = "openDoors", destroyMethod = "lockDoors")
    public DoorController doorController() {
        return new DoorController();
    }

    @Bean
    public CheckInDesk checkInDesk() {
        return new CheckInDesk();
    }
}

Quiz

1. In what order are the initialization methods of a bean that uses all three mechanisms called?

2. What sets a BeanFactoryPostProcessor apart from a BeanPostProcessor?

3. In which phase does Spring create the proxy for a bean with @Transactional methods?

4. A bean receives its Clock through an @Autowired setter and calls LocalTime.now(clock) in its constructor. What happens?

5. Why is it recommended to declare the @Bean method returning a BeanFactoryPostProcessor as static?

6. You close the context. In what order are the destruction callbacks of a singleton that uses all three called?

Cheatsheet → · Mock exam →

Run it