In this post we will learn about the spring bean life cycle callback methods.Spring container provides the below two callback methods for the bean,so that the bean can perform certain actions during initialization or on destruction of the bean.
Student - Spring bean class for which we will configure the callback methods.
CallbackDemo - Main class which loads the container and initializes the bean.
Studentcontext.xml - Metadata configuration details for the spring container.
Student.java
studentcontext.xml
As we can see in the application context file,we used the below two attributes in the bean definition of student.
We need to register the shutdownhook on the AbstractApplicationContext,so that the container will have the graceful shutdown and hence the corresponding destruction callback method on the bean will be called.
OUTPUT:
When we run the callbackDemo class, we will get the below output
As we can see in the output,spring container
- Initialization callback - After the bean is created by the container and the properties are set,the container will call this callback method.
- Destruction callback - when the bean is about to destroyed i.e when the container is about to exit,the container will call this callback method.
Student - Spring bean class for which we will configure the callback methods.
CallbackDemo - Main class which loads the container and initializes the bean.
Studentcontext.xml - Metadata configuration details for the spring container.
Student.java
studentcontext.xml
As we can see in the application context file,we used the below two attributes in the bean definition of student.
- init-method - This will configure the initialization callback method(which is init) for the student bean
- destroy-method - This will configure the destruction callback method(which is destroy) for the student bean
We need to register the shutdownhook on the AbstractApplicationContext,so that the container will have the graceful shutdown and hence the corresponding destruction callback method on the bean will be called.
OUTPUT:
When we run the callbackDemo class, we will get the below output
As we can see in the output,spring container
- invoked the initialization callback(init method), after the properties in the bean are set.
- invoked the destruction callback(destroy method) ,when the container is about to exit.
No comments:
Post a Comment