Video in progress
What are the main stages a bean goes through from creation to destruction?
Spring first creates the object, then injects its dependencies, calls the init callbacks and, if needed, wraps it in a proxy. When the context closes, the destroy callbacks run.
📖 Answer
A simplified order:
- Instantiation: the constructor is called (constructor injection happens here).
- Setter and field injection.
- Aware interfaces:
BeanNameAware,ApplicationContextAware. BeanPostProcessor(before).- Init:
@PostConstruct, thenInitializingBean.afterPropertiesSet(), then@Bean(initMethod = ...). BeanPostProcessor(after): the proxy for@Transactionaland@Asyncappears right here.- The bean is ready, and the application uses it.
- Destroy: when the context closes,
@PreDestroyandDisposableBean.destroy().
@Component
class ReportCache {
ReportCache(ReportRepository repo) { /* step 1 */ }
@PostConstruct
void warmUp() { /* step 5: all dependencies are ready */ }
@PreDestroy
void flush() { /* step 8 */ }
}
One subtle point: for prototype beans Spring doesn't call destroy. It creates the bean, hands it over and forgets about it. You close the resources yourself.
Sign up to mark studied questions and save your progress.