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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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;
    }
 
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
    }
}
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
2
3
<bean id="personService" class="com.kb.beans.PersonService" init-method="customInit" destroy-method="customDestroy">
<property name="person" ref="person"/>
</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

1
<beans default-init-method="customInit" default-destroy-method="customDestroy"/>
<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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;
        }
 
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
    }
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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>
<?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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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();
        
    }
 
}
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

Karibasappa G C (KB)
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