Life Cycle of a bean is fairy simple and a bit elaborate .When a
bean is instantiated, it may be required to perform some initialization to get
it into a usable state. Similarly, when the bean is no longer required and is
removed from the container, some cleanup may be required.
It is important to understand Bean life cycle to take advantage of some of the opportunities that Spring offers to customize how the bean is created.
Bean Provides Life cycle for both the container Bean Ffactory and Application Context. Here we will look into both the life cycles:
Life cycle of a bean within Spring Bean Factory:
a. Spring container finds the bean definition from the XML file and instantiates the bean.
b. Using the dependency injection, Spring populates all of the
properties as defined in the bean definition.
c. If the bean implements BeanNameAware interface then
Container calls
bean.setBeanName(bean id)
d. If the bean implements BeanFactoryAware interface then
Container calls bean.setBeanFactory(container)
e. If there are any BeanPostProcessors associated with the bean
Container calls postProcessBeforeInititialization() method
f. If bean instance of InitializingBean
1. Container
calls bean.afterPropertiesSet()
2. If bean declares custom init method
public class TestBean implements InitializingBean {
public void afterPropertiesSet() {
// do some
initialization work
}
}
2. If bean declares custom init method
1. Container
calls custom init() method of bean
g. If there are any BeanPostProcessors associated with the bean
Container calls postProcessAfterInititialization()
method
h. BEAN IS READY TO USE
After step h, the container has returned the bean to the
application, and the application works with the methods of the bean.
When the application is shutting down, it will result in the
container being destroyed too. Before that there are a few steps:
i. If bean instance of DisposableBean
1. Container
calls the bean.destroy()
public class ExampleBean implements DisposableBean {
public void destroy() {
// do some
destruction work
}
}
2. If
bean declares custom destroy method
1. Container
calls custom destroy() method of bean
j. BEAN IS READY FOR GARBAGE COLLECTION.
Life cycle of a bean within Spring Application Context:
The only difference here is that if the bean implements the ApplicationContext interface, the setApplicationContext() method is called.
No comments:
Post a Comment