Monday, September 6, 2010

Bean Lifecycle using BeanFactory And ApplicationContext

The following is the lifecycle of bean in ApplicationContext and BeanFactory:

1. Instantiate: Spring Instantiates the bean
2. Populate Properties: Spring injects the bean proprties
3. Set bean name: If the bean implements BeanNameAware, Spring passes the bean's ID to the setBeanName() method
4. Set bean factory: If the bean implements BeanFactoryAware, Spring passes the bean's factory to setBeanFactory() method
5. Set Application Context: If the bean implements ApplicationContextAware, the setApplicationContext() method will be called. Note: This is the only extra step that comes in the lifecycle of a bean using ApplicationConetxt container instead of BeanFactory
6. PostProcess (Before initialization): If there are any BeanPostProcessors, Spring calls their postProcessBeforeInitialization() method (Example is PropertPlaceHolderConfigurer)
7. Initialize Beans: If the bean implements InitializingBean, its afterPropertiesSet() method will be called. If the bean has a custom init-method defined in context file, that specific initializing method will be called.
8. PostProcess (After Initialization): If there are any BeanPostProcessors, Spring calls their postProcessAfterInitialization() method
9. Bean ready to use: At this point of time, the bean is ready to be used by the application and will remain until it is no longer needed.
10 Destroy Bean: If the bean implements DisposableBean, its destroy() method will be called. However, If the bean has a custom destroy-method defined in context file, that specific method will be called.

1 comment:

  1. A nice simple post, covering almost all important bean life cycle states in both scenarios.

    ReplyDelete