The Lifecycle of a Spring Bean
by, 11-16-2011 at 05:11 PM (1159 Views)
In this tip, we will look at the lifecycle of a bean. The bean lifecycle for a Spring bean is somewhat complex. It is important to understand the life cycle of a Spring bean. Otherwise it will be difficult for you as a programmer to use Spring to its full abilities especially because you may want to take advantage of some of the opportunities that Spring offers to customize how a bean is created. The startup life cycle of a typical bean as it is loaded into a BeanFactory container is shown:
- The container finds the beanís definition and instantiates the bean.
- Using dependency injection, Spring populates all of the properties as specified in the bean definition.
- If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the beanís ID.
- If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
- If there are any BeanPostProcessors associated with the bean, their post-ProcessBeforeInitialization() methods will be called.
- If an init-method is specified for the bean, it will be called.
- Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
The bean is now ready to be used by an application and will remain in the bean factory until it is no longer needed. It is removed from the bean factory in two ways.
- If the bean implements the DisposableBean interface, the destroy() method is called.
- If a custom destroy-method is specified, it will be called.
Now you should be in a position to add beans either via XML or programmatically for your application.