Tech Interview RoomStudy guides

Spring

Walk through the Spring bean lifecycle.

Advanced · 2 min read · Lesson 6 of 8 in Spring

Lifecycle of a singleton bean

  1. Bean definition loading: from component scanning, @Bean methods, auto-configuration. BeanFactoryPostProcessors run now and can modify definitions (for example PropertySourcesPlaceholderConfigurer resolves ${...}).
  2. Instantiation: the constructor is called (constructor injection happens here).
  3. Populate properties: setter and field injection.
  4. Aware callbacks: BeanNameAware, BeanFactoryAware, ApplicationContextAware.
  5. BeanPostProcessor.postProcessBeforeInitialization for every post-processor (this is where @PostConstruct is invoked, by CommonAnnotationBeanPostProcessor).
  6. Initialisation: @PostConstruct → InitializingBean.afterPropertiesSet() → custom initMethod.
  7. BeanPostProcessor.postProcessAfterInitialization: AOP proxies are created here. The object stored in the context may be a proxy wrapping your bean, which is how @Transactional, @Async and @Cacheable work.
  8. Bean is ready; SmartInitializingSingleton and ContextRefreshedEvent fire after all singletons are created.
  9. Destruction on context close: @PreDestroy → DisposableBean.destroy() → custom destroyMethod.

Prototype beans go through creation and initialisation, but Spring does not manage their destruction.

Example

java
@Component
class PriceCache {
    private final PriceClient client;
    private Map<String, BigDecimal> prices;

    PriceCache(PriceClient client) { this.client = client; }                // 2. instantiate + inject

    @PostConstruct void warmUp() { prices = client.loadAll(); }            // 6. dependencies are ready here
    @PreDestroy   void flush()  { prices.clear(); }                         // 9. on shutdown
}

Follow-up questions interviewers ask

Try answering each one before you open it.

BeanFactoryPostProcessor vs BeanPostProcessor?

A BeanFactoryPostProcessor runs before any bean is created and works on bean definitions (metadata): changing property values, registering more definitions. A BeanPostProcessor runs for each bean instance after it is created and can modify or wrap the instance (proxies, validation, injecting annotations). Declare BFPPs as static @Bean methods so they do not force early creation of their configuration class.

Why can't you call a @Transactional method from @PostConstruct and expect a transaction?

@PostConstruct runs in step 6, on the raw target object, before the proxy is created in step 7, so this.someTransactionalMethod() bypasses the proxy and runs without a transaction. Do such work after startup instead: an ApplicationRunner, a listener for ApplicationReadyEvent, or by calling through another bean.