Walk through the Spring bean lifecycle.
Lifecycle of a singleton bean
- Bean definition loading: from component scanning,
@Beanmethods, auto-configuration.BeanFactoryPostProcessors run now and can modify definitions (for examplePropertySourcesPlaceholderConfigurerresolves${...}). - Instantiation: the constructor is called (constructor injection happens here).
- Populate properties: setter and field injection.
- Aware callbacks:
BeanNameAware,BeanFactoryAware,ApplicationContextAware. BeanPostProcessor.postProcessBeforeInitializationfor every post-processor (this is where@PostConstructis invoked, byCommonAnnotationBeanPostProcessor).- Initialisation:
@PostConstruct→InitializingBean.afterPropertiesSet()→ custominitMethod. BeanPostProcessor.postProcessAfterInitialization: AOP proxies are created here. The object stored in the context may be a proxy wrapping your bean, which is how@Transactional,@Asyncand@Cacheablework.- Bean is ready;
SmartInitializingSingletonandContextRefreshedEventfire after all singletons are created. - Destruction on context close:
@PreDestroy→DisposableBean.destroy()→ customdestroyMethod.
Prototype beans go through creation and initialisation, but Spring does not manage their destruction.
Example
@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.