Search This Blog

Monday, 16 April 2012

The Bean Lifecycle

I was studying the life cycle of the bean in a Spring application. The Spring container performs several step in the bean creation process before making it available to the use for the application.
I created a small algorithm detailing the creation process below:
  1. Spring Container instantiates the bean 
  2.  It populates the bean properties
  3. If (bean instance of BeanNameAware)
    1. Container calls bean.setBeanName(bean id)
  4. If (bean instance of BeanFactoryAware)
    1.  Container calls bean.setBeanFactory(container)
  5.  If (bean instance of ApplicationContextFactoryAware)
    1.  Container calls bean.setApplicationContext(container)
  6. If (container has BeanPostProcessors)
    1. Container calls postProcessBeforeInititialization() method of   BeanPostProcessors
  7. If (bean instance of InitializingBean)
    1. Container calls bean.afterPropertiesSet()
    2.  If bean declares custom init method
      1. Container calls custom init method of bean
  8. If (container has BeanPostProcessors)
    1. Container calls postProcessAfterInititialization() method of   BeanPostProcessors
  9. Bean is now READY FOR USE
While step 4 occurs when the BeanFactory is used, step 5 occurs only when working with the ApplicationContext. Rest of the steps are a part of every beans initialization flow. After step 9, the container has returned the bean to the application, and the application works with the methods of the bean.
Similarly when the application is shutting down, it will result in the container being destroyed too. Naturally the beans are also approaching the end of their lifecycle. Before that there are a few steps:
  1. If (bean instance of DisposableBean)
    1. Container calls the bean.destroy()
    2.  If bean declares custom destroy method
      1. Container calls custom destroy method of bean
  2. Bean is ready for garbage collection.

8 comments:

  1. very good explanation

    ReplyDelete
  2. Nice Algo .. Thanks for sharing

    ReplyDelete
  3. thanks.
    good algorithm.

    ReplyDelete
  4. super.......

    ReplyDelete
  5. Hi its a good explanation, you have missed BeanClassLoaderAware interface if you could add it will be complete information. Any how nice explanation

    ReplyDelete
  6. Nice elaboration...

    ReplyDelete