Video in progress

Junior 🌱 Spring

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:

  1. Instantiation: the constructor is called (constructor injection happens here).
  2. Setter and field injection.
  3. Aware interfaces: BeanNameAware, ApplicationContextAware.
  4. BeanPostProcessor (before).
  5. Init: @PostConstruct, then InitializingBean.afterPropertiesSet(), then @Bean(initMethod = ...).
  6. BeanPostProcessor (after): the proxy for @Transactional and @Async appears right here.
  7. The bean is ready, and the application uses it.
  8. Destroy: when the context closes, @PreDestroy and DisposableBean.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.