Spring
May 27, 2020

M01 Q07 Can you describe the lifecycle of a Spring Bean in an ApplicationContext?

Context is created:

To analyze the lifecycle of the bean in Application Context first we need to check how the bean definitions are created.

  1. Beans Definitions are created based on Spring Bean Configuration. To create a bean definition they need to be read from Spring Bean Configuration. Spring Bean Configuration can be supplied via XML or annotation config.
  2. BeanFactoryPostProcessors are invoked. All of the bean definitions can be post-processed by the objects that are implementing the BeanFactoryPostProcessor interface. On this level Spring gives you an ability to access any of the bean definition.

Bean is Created:

After that, you have the bean definitions and Spring will start creating the Spring bean objects.

  1. The instance of the bean is created
  2. Properties and dependencies are set.
  3. BeanPostProcessor::postProcessBeforeInitialization gets called. This is a chance to customize the bean object before it will be used.
  4. @PostConstruct method gets called.
  5. InitializingBean::afterPropertiesSet method gets called.
  6. @Bean(initMethod) method gets called.
  7. BeanPostProcessor::postProcessAfterInitialization gets called.

Bean is ready to use.

Bean is destroyed:

Bean will be destroyed when the Application Context will get closed.

  1. @PreDestroy method gets called
  2. DisposableBean::destroy method gets called
  3. @Bean(destroyMethod) method gets called