InitializingBean and DisposableBean, Custom init-method and custom destroy-method

InitializingBean interface has one method afterPropertiesSet() which is called after all the properties of a bean are set.

DisposableBean interface has one method destroy() which is called before the bean gets destroyed or before it gets removed from the application context.

Let us write a UserService class which implements above interfaces

  1. package com.kb.beans;
  2.  
  3. import org.springframework.beans.factory.DisposableBean;
  4. import org.springframework.beans.factory.InitializingBean;
  5.  
  6. public class UserService implements InitializingBean,DisposableBean {
  7.  
  8.     private User user;
  9.    
  10.     public UserService() {
  11.     System.out.println("UserService no-arg constructor");
  12.     }
  13.  
  14.     public void destroy() throws Exception {
  15.         System.out.println("UserService destroy method - closing opened resources");
  16.        
  17.     }
  18.  
  19.     public void afterPropertiesSet() throws Exception {
  20.         if(!user.getName().equals("Ram")){
  21.             user.setName("Ram");
  22.         }
  23.         System.out.println("UserService afterPropertiesSet method");
  24.        
  25.     }
  26.  
  27.     public User getUser() {
  28.         return user;
  29.     }
  30.  
  31.     public void setUser(User user) {
  32.         this.user = user;
  33.     }
  34.  
  35. }
package com.kb.beans;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class UserService implements InitializingBean,DisposableBean {

	private User user;
	
	public UserService() {
	System.out.println("UserService no-arg constructor");
	}

	public void destroy() throws Exception {
		System.out.println("UserService destroy method - closing opened resources");
		
	}

	public void afterPropertiesSet() throws Exception {
		if(!user.getName().equals("Ram")){
			user.setName("Ram");
		}
		System.out.println("UserService afterPropertiesSet method");
		
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

}

Create a class called User

  1. package com.kb.beans;
  2.  
  3. import org.springframework.beans.BeansException;
  4. import org.springframework.beans.factory.config.BeanPostProcessor;
  5.  
  6. public class User {
  7.  
  8.     private String name;
  9.  
  10.     public String getName() {
  11.         return name;
  12.     }
  13.  
  14.     public void setName(String name) {
  15.         this.name = name;
  16.     }
  17. }
package com.kb.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class User {

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

Custom init-method and destroy-method

Custom init method is called after the bean is initialized and custom destroy method is called before the bean is destroyed.

We can define the custom init and destroy methods in 2 ways.

One is for a single bean and other is for all the beans

To make it for single bean, we use the code like below

  1. <bean id="personService" class="com.kb.beans.PersonService" init-method="customInit" destroy-method="customDestroy">
  2. <property name="person" ref="person"/>
  3. </bean>
<bean id="personService" class="com.kb.beans.PersonService" init-method="customInit" destroy-method="customDestroy">
<property name="person" ref="person"/>
</bean>

Then we must define these customInit and customDestroy methods inside this bean class.

To make it for all the beans, we can write code like below

<beans default-init-method="customInit" default-destroy-method="customDestroy"/>

Then we must define these customInit and customDestroy methods inside each bean class
In this case we must use the same method names for all the beans.

Lets create PersonService class as below

  1. package com.kb.beans;
  2.  
  3. public class PersonService {
  4.    
  5.     private Person person;
  6.    
  7.     public PersonService() {
  8.         System.out.println("PersonService no-arg constructor");
  9.     }
  10.    
  11.       public void customInit()
  12.         {
  13.             System.out.println("customInit() called");
  14.         }
  15.      
  16.         public void customDestroy()
  17.         {
  18.             if(!person.getName().equals("Raj")){
  19.                 person.setName("Raj");
  20.             }
  21.             System.out.println("customDestroy() called , closing opened resources");
  22.         }
  23.  
  24.         public Person getPerson() {
  25.             return person;
  26.         }
  27.  
  28.         public void setPerson(Person person) {
  29.             this.person = person;
  30.         }
  31.  
  32. }
package com.kb.beans;

public class PersonService {
	
	private Person person;
	
	public PersonService() {
		System.out.println("PersonService no-arg constructor");
	}
	
	  public void customInit()
	    {
	        System.out.println("customInit() called");
	    }
	 
	    public void customDestroy()
	    {
	    	if(!person.getName().equals("Raj")){
	    		person.setName("Raj");
			}
	        System.out.println("customDestroy() called , closing opened resources");
	    }

		public Person getPerson() {
			return person;
		}

		public void setPerson(Person person) {
			this.person = person;
		}

}


Create a Person class

  1. package com.kb.beans;
  2.  
  3. import org.springframework.beans.BeansException;
  4. import org.springframework.beans.factory.config.BeanPostProcessor;
  5.  
  6. public class Person {
  7.    
  8.     private String name;
  9.    
  10.     public void setName(String name) {
  11.         this.name = name;
  12.     }
  13.  
  14.     public String getName() {
  15.         return name;
  16.     }
  17. }
package com.kb.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class Person {
	
	private String name;
	
	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
}

Create the spring beans.xml file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:p="http://www.springframework.org/schema/p"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8.        http://www.springframework.org/schema/context
  9.         http://www.springframework.org/schema/context/spring-context-3.2.xsd">
  10.  
  11.     <!-- <context:annotation-config/> -->
  12.     <bean id="person" class="com.kb.beans.Person">
  13.         <property name="name" value="Raj"/>
  14.     </bean>
  15.    
  16.     <bean id="user" class="com.kb.beans.User">
  17.     <property name="name" value="Ram"/>
  18.     </bean>
  19.    
  20.     <bean id="personService" class="com.kb.beans.PersonService" init-method="customInit" destroy-
  21.                                                                          method="customDestroy">
  22.     <property name="person" ref="person"/>
  23.     </bean>
  24.    
  25.     <bean id="userService" class="com.kb.beans.UserService">
  26.     <property name="user" ref="user"/>
  27.     </bean>
  28.    
  29. </beans>
<?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:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
  		http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<!-- <context:annotation-config/> -->
	<bean id="person" class="com.kb.beans.Person">
		<property name="name" value="Raj"/>
	</bean>
	
	<bean id="user" class="com.kb.beans.User">
	<property name="name" value="Ram"/>
	</bean>
	
	<bean id="personService" class="com.kb.beans.PersonService" init-method="customInit" destroy-
                                                                         method="customDestroy">
	<property name="person" ref="person"/>
	</bean>
	
	<bean id="userService" class="com.kb.beans.UserService">
	<property name="user" ref="user"/>
	</bean>
	
</beans>


Create the BeanLifeCycle class as below

  1. package com.kb.beans;
  2.  
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5.  
  6.  
  7. public class BeansLifeCycle {
  8.  
  9.     public static void main(String[] args) {
  10.  
  11.         ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml");  
  12.        
  13.         //Load PersonService object
  14.         PersonService personService = (PersonService)applicationContext.getBean("personService");
  15.         System.out.println("Name : "+personService.getPerson().getName());
  16.        
  17.         //Load UserService object
  18.         UserService userService = (UserService)applicationContext.getBean("userService");
  19.         System.out.println("Name : "+userService.getUser().getName());
  20.        
  21.         applicationContext.registerShutdownHook();
  22.        
  23.     }
  24.  
  25. }
package com.kb.beans;

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


public class BeansLifeCycle {

	public static void main(String[] args) {

		ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml");  
		
		//Load PersonService object
		PersonService personService = (PersonService)applicationContext.getBean("personService");
        System.out.println("Name : "+personService.getPerson().getName());
        
        //Load UserService object
        UserService userService = (UserService)applicationContext.getBean("userService");
        System.out.println("Name : "+userService.getUser().getName());
        
        applicationContext.registerShutdownHook();
        
	}

}


Run this class and see the output as below


Download this project Init-and-Destroy-methods.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on