Spring lifetime callbacks

This is 13 of 16 parts of tutorial series

Tutorial Content:

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial
The Spring Framework provides several callback interfaces to change the behavior of your bean in the container; they include InitializingBean and DisposableBean.

The life cycle of a Spring bean is easy to understand. 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.

Initialization callbacks:

Implementing the org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container. The InitializingBean interface specifies exactly one method:

void afterPropertiesSet() throws Exception; 


Generally, the use of the InitializingBean interface can be avoided and is actually discouraged since it unnecessarily couples the code to Spring.You have to use  afterPropertiesSet(),you can not change name of method.There is alternative for this i.e. XML-based configuration metadata.This is done using the 'init-method' attribute of <bean> tag.It provides flexibility of changing method name.

<bean id="countryBean" class="org.arpit.javapostsforlearning.Country" init-method="init"/>

public class Country{
    
    public void init() {
        // do some initialization work
    }
} 
...is exactly the same as...

<bean id="countryBean" class="org.arpit.javapostsforlearning.Country"/>

public class Country implements InitializingBean {
    
    public void afterPropertiesSet() {
        // do some initialization work
    }
} 
... but does not couple the code to Spring.

Destruction callbacks:

Implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed. The DisposableBean interface specifies a single method:

void destroy() throws Exception; 

 Generally, the use of the DisposableBean interface can be avoided and is actually discouraged since it unnecessarily couples the code to Spring.You have to use  destroy(),you can not change name of method.There is alternative for this i.e. XML-based configuration metadata.This is done using the 'destroy-method' attribute of <bean> tag.It provides flexibility of changing method name.

<bean id="countryBean" class="org.arpit.javapostsforlearning.Country" init-method="destroy"/>

public class Country{
    
    public void destroy() {
        // do some destruction work(like releasing pooled connections)
    }
} 
...is exactly the same as...

<bean id="countryBean" class="org.arpit.javapostsforlearning.Country"/>

public class Country implements DisposableBean{
    
    public void destroy() {
        // do some destruction work(like releasing pooled connections)   
 }
} 
... but does not couple the code to Spring.

Example:

For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;

public class Country {

 String countryName ;
 
 public String getCountryName() {
  return countryName;
 }
 
 
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }

 public void init()
 {
  System.out.println("In init block of country");
 }

 public void destroy()
 {
  System.out.println("In destroy block of country");
 }
}

2.LifetimeCallbacksMain.java

This class contains main function.Create LifetimeCallbacksMain.java under package org.arpit.javapostsforlearning.Copy following content into LifetimeCallbacksMain.java
package org.arpit.javapostsforlearning;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class LifetimeCallbacksMain{

 public static void main(String[] args) {

  AbstractApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
  Country countryObj = (Country) appContext.getBean("country");
  System.out.println("Country Name: "+countryObj.getCountryName());
  appContext.registerShutdownHook();
 }
}
Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.

3.ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="country" class="org.arpit.javapostsforlearning.Country" init-method="init" destroy-method="destroy">
 <property name="countryName" value="India"/>
 </bean>
  
</beans>

4.Run it

When you will run above application,you will get following as output.


In init block of country
Country Name: India
In destroy block of country

Default Initialization and destroy method:

If you have too many beans having initialization and or destroy methods with the same name, you don't need to declare init-method and destroy-method on each individual bean. Instead framework provides the flexibility to configure such situation using default-init-method and default-destroy-method attributes on the <beans> element as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
 default-init-method="init"
 default-destroy-method="destroy"
 >
 
 <bean id="country" class="org.arpit.javapostsforlearning.Country">
 <property name="countryName" value="India"/>
 </bean>
  
</beans>





 

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012