The 30 second answer
For a typical singleton, Spring constructs the object, resolving constructor dependencies, then injects fields and setters. It calls Aware callbacks and runs initialization post-processors, including the one that invokes @PostConstruct. Next come InitializingBean's afterPropertiesSet and any custom init method, followed by post-processors that can wrap the bean in an AOP proxy. On context shutdown, Spring runs @PreDestroy, DisposableBean's destroy callback and any custom destroy method. Prototype beans don't get automatic destruction callbacks.
The core order is in AbstractAutowireCapableBeanFactory.doCreateBean:
instanceWrapper = createBeanInstance(beanName, mbd, args); // 1. instantiate
...
populateBean(beanName, mbd, instanceWrapper); // 2. inject
exposedObject = initializeBean(beanName, exposedObject, mbd); // 3. initialize
...
registerDisposableBeanIfNecessary(beanName, bean, mbd); // 4. register destroyAbstractAutowireCapableBeanFactory.java L565, L602-L603, L641
And initializeBean shows the initialization order:
invokeAwareMethods(beanName, bean);
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
invokeInitMethods(beanName, wrappedBean, mbd);
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;AbstractAutowireCapableBeanFactory.initializeBean L1797-L1822
Full order:
- Bean definition is registered (from scanning,
@Beanor auto-configuration).BeanFactoryPostProcessors can change definitions before any bean exists. - Instantiation: constructor call; constructor injection resolves dependencies here.
- Population:
@Autowiredfields and setters,@Value. - Aware callbacks:
BeanNameAware,BeanClassLoaderAware,BeanFactoryAware. (ApplicationContextAwareand similar are handled by a post-processor in step 5.) - **
postProcessBeforeInitialization**:CommonAnnotationBeanPostProcessorcalls@PostConstructhere. - Init:
InitializingBean.afterPropertiesSet(), then@Bean(initMethod = ...). - **
postProcessAfterInitialization**: AOP proxies for@Transactional,@Async,@Cacheableare created here. The object stored in the container may be a proxy, not your instance. - Ready: after all singletons exist,
SmartInitializingSingleton.afterSingletonsInstantiated()runs;SmartLifecyclebeans start. - Destroy (on context close):
@PreDestroy,DisposableBean.destroy(), custom destroy method.
Scope matters: prototype beans go through steps 1โ7 each time, but the container does not call their destroy callbacks.
Classic follow-up: why does @Transactional not work on a self-call? Because the proxy is made in step 7. A call to this.method() goes to the raw object, not the proxy.