Spring Bean Life Cycle
Let us understand Life Cycle of a bean in Spring
The beans life cycle in spring is one of the most important features to understand.
In many of the real time applications, it is necessary to perform some of the operations before initializing a bean and it is necessary to perform some cleanup operations before the bean is destroyed by the container.
In Java, The life cycle of an object begins with new keyword.
When we create an object using new , that time it calls the series of hierarchical class constructors(call goes from bottom to top and hence execution from top to bottom)
And finally makes the object available.
And when this object will not have any reference, it will be garbage collected. This is the simple life cycle of an object in Java.
But in spring, Bean’s life cycle is having few more things to do.
The spring bean’s life cycle is as shown below
1) Spring container looks for the definition of the bean in the spring configuration xml file
2) Spring instantiate the bean by calling no argument default constructor of that class,
If there is only parameterized constructor in the class , then bean must be defined in spring xml file with constructor injection using which container will instantiate the bean otherwise it will throw bean creation exception.
2) Spring injects the values and references if any into bean’s properties.
3) If the bean implements BeanNameAware interface, Spring passes the bean’s ID to the setBeanName () method and executes this method.
4) If the bean implements BeanFactoryAware interface, Spring calls the setBeanFactory () method, passing in the bean factory itself and executes this method.
5) If the bean implements ApplicationContextAware interface, Spring will call the setApplicationContext () method, passing in a reference to the current application context and executes this method.
6) If the bean implements the BeanPostProcessor interface, Spring calls their postProcessBeforeInitialization () method
7)If the bean implements the InitializingBean interface, Spring calls afterPropertiesSet() method after all the properties of that bean are set.
Similarly, if the bean is declared with an init-method, then the specified initialization method will be called
8) If the bean implements BeanPostProcessor, Spring will call their postProcessAfterInitialization() method.
9) At this point, the bean is ready to be used by the application and will remain in the application context until the application context is destroyed.
10) If the bean implements the DisposableBean interface, then Spring will call the destroy() method. Likewise, if any bean was declared with a destroy-method, then the specified method will be called.
We will see each of these life cycle methods in detail in the next post.