Spring Bean Life Cycle – Bean Initialization and Destruction
Spring IoC container is also responsible for managing the Spring Bean Life Cycle, the life cycle of beans consist of call back methods such as Post initialization call back method and Pre destruction call back method. Below steps are followed by Spring IoC Container to manage bean life cycle.
Spring Bean Life Cycle
1. Creation of bean instance by a factory method.
2. Set the values and bean references to the bean properties.
3. Call the initialization call back method.
4. Bean is ready for use.
5. Call the destruction call back method.
Spring can recognize the initialization and destruction callback methods in the below three ways.
1. A Bean can implement the InitializingBean and DisposableBean life cycle interfaces and overriding the afterPropertiesSet() (Called during Spring bean initialization) and destroy() methods for initialization and destruction respectively.
2. Set the init-method and destroy-method attributes in the bean configuration file.
3. Use @PostConstruct and @PreDestroy over the methods (Spring 2.5 or later) which is defined in JSR-250.
Lets learn about each one of them one by one.
1. Implementing InitializingBean and DisposableBean Interfaces
When are implement the InitializingBean and DisposableBean interfaces in our bean, Spring allows our bean to perform the task mentioned initialization and destruction methods afterPropertiesSet() and destroy(). During the construction you can notice Spring will be calling those methods at a suitable time of Spring bean life cycle.
1. Create a new Java Project “SpringCoreTutorial” and create a package for our src files “com.aid“
2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.
commons-logging-1.2.jar
spring-beans-4.2.4.RELEASE.jar
spring-core-4.2.4.RELEASE.jar
spring-context-4.2.4.RELEASE.jar
spring-expression-4.2.4.RELEASE.jar
3. Create the Java classes InitializeDestroyExample.java and Logic.java under com.aid folder.
4. Place our configuration file SpringConfig.xml in the src directory
SpringConfig.xml
In order to declare beans in the Spring IoC container via XML, we must create an XML configuration file (SpringConfig.xml). The configuration file must be put in the srcdirectory.
InitializeDestroyExample.java
In our InitializeDestroyExample class we have implemented the InitializingBean and DisposableBean interfaces and overridden the afterPropertiesSet() and destroy()methods. We have a concrete method display() which displays the welcome message.
Logic.java
• In our Logic class we have read the Configuration file(SpringConfig.xml) and get all the bean definition through ApplicationContext
• Get the InitializeDestroyExample Class instance by calling the getBean()method over the context created.
• Call the display() which prints the welcome message.
• Finally Close the application context which we have created.
Output :
2. init-method and destroy-method Attributes in the Configuration file
In the above way we are forced to implement the InitializingBean and DisposableBean interfaces and overridde the afterPropertiesSet() and destroy()methods. By setting the init-method and destroy-method attribute in the configuration file. we can have our own custom method acting as a initializing and destroy method. Lets now re-write the InitializeDestroyExample class.
InitializeDestroyExample.java
We have written our own methods intializationMethod() and destroyMethod() for spring bean initialization and spring bean destruction respectively.
Now corresponding changes has to be made in our configuration file
We have added the init-method attribute value as “initializationMethod” for initialization and destroy-method attribute value as “destroyMethod” for destruction.
Output :
Upon running our Logic class we will be getting the below output.
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Initialization method called
Welcome to Aid!!!
Jun 20, 2016 5:02:37 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@544764a1: startup date [Mon Jun 20 17:02:37 IST 2016]; root of context hierarchy
Destroy method called
3. Using @PostConstruct and @PreDestroy Annotations
Using the @PostConstruct and @PreDestroy annotation would be much simpler approach those are the spring bean life cycle annotation, we can remove of the init-method and destroy-method attribute in our configuration file and simply add the @PostConstruct annotation over the method which you want to be called after spring bean initialization and @PreDestroy over the method which has to be called before the context is destroyed.
IntializeDestroyExample
Once we run our Logic class we will be getting the same above output.
Spring IoC container is also responsible for managing the Spring Bean Life Cycle, the life cycle of beans consist of call back methods such as Post initialization call back method and Pre destruction call back method. Below steps are followed by Spring IoC Container to manage bean life cycle.
Spring Bean Life Cycle
1. Creation of bean instance by a factory method.
2. Set the values and bean references to the bean properties.
3. Call the initialization call back method.
4. Bean is ready for use.
5. Call the destruction call back method.
Spring can recognize the initialization and destruction callback methods in the below three ways.
1. A Bean can implement the InitializingBean and DisposableBean life cycle interfaces and overriding the afterPropertiesSet() (Called during Spring bean initialization) and destroy() methods for initialization and destruction respectively.
2. Set the init-method and destroy-method attributes in the bean configuration file.
3. Use @PostConstruct and @PreDestroy over the methods (Spring 2.5 or later) which is defined in JSR-250.
Lets learn about each one of them one by one.
1. Implementing InitializingBean and DisposableBean Interfaces
When are implement the InitializingBean and DisposableBean interfaces in our bean, Spring allows our bean to perform the task mentioned initialization and destruction methods afterPropertiesSet() and destroy(). During the construction you can notice Spring will be calling those methods at a suitable time of Spring bean life cycle.
1. Create a new Java Project “SpringCoreTutorial” and create a package for our src files “com.aid“
2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.
commons-logging-1.2.jar
spring-beans-4.2.4.RELEASE.jar
spring-core-4.2.4.RELEASE.jar
spring-context-4.2.4.RELEASE.jar
spring-expression-4.2.4.RELEASE.jar
3. Create the Java classes InitializeDestroyExample.java and Logic.java under com.aid folder.
4. Place our configuration file SpringConfig.xml in the src directory
SpringConfig.xml
In order to declare beans in the Spring IoC container via XML, we must create an XML configuration file (SpringConfig.xml). The configuration file must be put in the srcdirectory.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config></context:annotation-config> <bean id="initdest" class="com.aid.InitializeDestroyExample"></bean> </beans>We have made an entry for our bean “InitializeDestroyExample” with id “initdest”.
InitializeDestroyExample.java
package com.aid; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; public class InitializeDestroyExample implements InitializingBean, DisposableBean { @Override public void afterPropertiesSet() throws Exception { System.out.println("Initialization method called"); } @Override public void destroy() throws Exception { System.out.println("Destroy method called"); } public void display() { System.out.println("Welcome to Aid!!!"); } }
In our InitializeDestroyExample class we have implemented the InitializingBean and DisposableBean interfaces and overridden the afterPropertiesSet() and destroy()methods. We have a concrete method display() which displays the welcome message.
Logic.java
package com.aid; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Logic { public static void main(String args[]) { // Read the Configuration file using ApplicationContext AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext("SpringConfig.xml"); // Get the InitializeDestroyExample class instance InitializeDestroyExample id = (InitializeDestroyExample) applicationContext.getBean("initdest"); // Call the display() method id.display(); // Closing the context applicationContext.close(); } }
• In our Logic class we have read the Configuration file(SpringConfig.xml) and get all the bean definition through ApplicationContext
• Get the InitializeDestroyExample Class instance by calling the getBean()method over the context created.
• Call the display() which prints the welcome message.
• Finally Close the application context which we have created.
Output :
2. init-method and destroy-method Attributes in the Configuration file
In the above way we are forced to implement the InitializingBean and DisposableBean interfaces and overridde the afterPropertiesSet() and destroy()methods. By setting the init-method and destroy-method attribute in the configuration file. we can have our own custom method acting as a initializing and destroy method. Lets now re-write the InitializeDestroyExample class.
InitializeDestroyExample.java
package com.aid; public class InitializeDestroyExample { public void initializationMethod() { System.out.println("Initialization method called"); } public void display() { System.out.println("Welcome to Aid!!!"); } public void destroyMethod() { System.out.println("Destroy method called"); } }
We have written our own methods intializationMethod() and destroyMethod() for spring bean initialization and spring bean destruction respectively.
Now corresponding changes has to be made in our configuration file
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config></context:annotation-config> <bean id="initdest" class="com.aid.InitializeDestroyExample" init-method="initializationMethod" destroy-method="destroyMethod"/> </beans>
We have added the init-method attribute value as “initializationMethod” for initialization and destroy-method attribute value as “destroyMethod” for destruction.
Output :
Upon running our Logic class we will be getting the below output.
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Initialization method called
Welcome to Aid!!!
Jun 20, 2016 5:02:37 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@544764a1: startup date [Mon Jun 20 17:02:37 IST 2016]; root of context hierarchy
Destroy method called
3. Using @PostConstruct and @PreDestroy Annotations
Using the @PostConstruct and @PreDestroy annotation would be much simpler approach those are the spring bean life cycle annotation, we can remove of the init-method and destroy-method attribute in our configuration file and simply add the @PostConstruct annotation over the method which you want to be called after spring bean initialization and @PreDestroy over the method which has to be called before the context is destroyed.
IntializeDestroyExample
package com.aid; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; public class InitializeDestroyExample { @PostConstruct public void initializationMethod() { System.out.println("Initialization method called"); } public void display() { System.out.println("Welcome to Aid!!!"); } @PreDestroy public void destroyMethod() { System.out.println("Destroy method called"); } }
Once we run our Logic class we will be getting the same above output.