Home Navigation

Friday 10 July 2020

Spring bean life cycle overview

Spring beans are components which are handled and managed by spring IoC container. When the beans get created it is required to perform some initialization to get the beans usable. And when beans are no longer required and gets removed from IoC needs some clean up.

We define beans in three ways
  • XML Config (Load xml definitions ) -> instantiation & constr injection -> property injection
  • Annotation config ( @Component scanning) -> instantiation & @Autowired on constructor -> injection of @Autowired methods & fields
  • Java Config ( Read @Bean method signature ) -> call @Bean method implementations

We can divide the life cycle of a bean as below

Callback Interfaces
  • InitializingBean.afterPropertiesSet() called after properties are set
  • DisposableBean.destroy() called during bean destruction in shutdown
Life Cycle Annotations
  • @PostConstruct annotated methods will be called after the bean has been constructed, but before its returned to the requesting object   
  • @PreDestroy is called just before the bean is destroyed by the container
Bean Post Processors
  • Gives you a means to tap into the Spring context life cycle and interact with beans as they are processed
  • postProcessBeforeInitialization - Called before bean initialization method
  • postProcessAfterInitialization - Called after bean initialization
‘Aware’ Interfaces
  • Spring has over 14 ‘Aware’ interfaces.
  • These are used to access the Spring Framework infrastructure
  • These are largely used within the framework
  • Rarely used by Spring developers


Note: BeanFactoryPostProcessor implementations are "called" during startup of the Spring context after all bean definitions will have been loaded while BeanPostProcessor are "called" when the Spring IoC container instantiates a bean.

BeanFactoryPostProcessor kicks in at the phase of the container life-cycle, when no bean has been created but the bean definition has already been parsed, while BeanPostProcessor comes into play after bean creation.

No comments:

Post a Comment