Spring Bean Initialization And Destruction Examples

Spring framework provide three methods for you to customize bean behavior after bean initialization and before destruction. Of course all the methods are invoked by spring bean factory. This article will tell you how to do that by examples.

Methods To Customize Bean Post Initialization And Pre Destruction Behavior 

  1. Define bean with init() and destroy() methods in spring bean configuration file.
  2. Annotate initialization method with @javax.annotation.PostConstruct and destruction method with @javax.annotation.PreDestroy in bean java file.
  3. Let bean implements InitializingBean and DisposableBean interfaces.

1. Define init() and destroy() method in bean configuration file example.

  1. First define init-method and destroy-method properties in bean definition as below.
    spring bean init and destroy with bean configuration properties xml fileBeanSettings.xml

    <bean id="initAndDestroyExampleByConfiguration" name="initAndDestroyExampleByConfiguration" 
          init-method="postInitMethod" destroy-method="preDestroyMethod" 
          class="com.dev2qa.example.spring.bean.initdestroy.InitAndDestroyExampleByConfiguration"> 
    </bean>
  2. Second implement above defined method in java file.
    InitAndDestroyExampleByConfiguration.java

    public class InitAndDestroyExampleByConfiguration {
    	
    	public void postInitMethod()
    	{
    		System.out.println("This is bean post init method which will run immediately after initialization. ");
    	}
    
    	public void preDestroyMethod()
    	{
    		System.out.println("This is bean pre destroy method which will run just before destroy. ");
    	}
    	
    	public void pringHello()
    	{
    		System.out.println("hello");
    	}
    	
    	public static void main(String args[])
    	{
    	   	// Initiate Spring application context, this line code will invoke bean initialize method.
    		ApplicationContext springAppContext = new ClassPathXmlApplicationContext("BeanSettings.xml");
    
    		// Get InitAndDestroyExampleByConfiguration by id. 
    		InitAndDestroyExampleByConfiguration exampleBean = (InitAndDestroyExampleByConfiguration) springAppContext.getBean("initAndDestroyExampleByConfiguration");
    		
    		// Call bean methods.
    		exampleBean.pringHello();
    		
    		// Close spring context, this line code will invoke the bean destroy methods.
    		((ClassPathXmlApplicationContext) springAppContext).close(); 
    		
    	}
    }
    
  3. Output.
    spring bean init and destroy with bean configuration output

2. Use @PostConstruct and @PreDestroy example.

    1. You should add xml namespace context in beans definition file, and add <context:annotation-config/> xml tag. Then you can define bean in it.
      spring init and destroy use javax annotation

      <?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:p="http://www.springframework.org/schema/p" 
             xmlns:context="http://www.springframework.org/schema/context" 
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">     
      
             <context:annotation-config />
             
             <bean id="initAndDestroyByAnnotation" name="initAndDestroyByAnnotation" 
                   class="com.dev2qa.example.spring.bean.initdestroy.InitAndDestroyByAnnotation"> 
             </bean>
      </beans>
    2. Define init and destroy method in java file with javax annotation.
      public class InitAndDestroyByAnnotation {
      
      	public static void main(String[] args) {
      	   	// Initiate Spring application context, this line code will invoke bean initialize method.
      		ApplicationContext springAppContext = new ClassPathXmlApplicationContext("BeanSettings.xml");
      
      		// Get InitAndDestroyByAnnotation by id. 
      		InitAndDestroyByAnnotation exampleBean = (InitAndDestroyByAnnotation) springAppContext.getBean("initAndDestroyByAnnotation");
      		
      		exampleBean.print();
      		
      		// Close spring context, this line code will invoke the bean destroy methods.
      		((ClassPathXmlApplicationContext) springAppContext).close(); 
      	}
      
      	@PostConstruct
      	public void postInit()
      	{
      		System.out.println("This is bean post init method annotated by @PostConstruct. ");
      	}
      
      	@PreDestroy
      	public void preDestroy()
      	{
      		System.out.println("This is bean pre destroy method annotated by @PreDestroy. ");
      	}
      	
      	
      	public void print()
      	{
      		System.out.println("Init and destroy use annotation. ");
      	}
      	
      }
      
    3. Output.
      spring init and destroy use javax annotation output
READ :   Spring MVC Multiple File Upload Example

3. Implement org.springframework.beans.factory.InitializingBean and org.springframework.beans.factory.DisposableBean interface.

This is not the recommended method because it is highly coupled with Spring framework. If you select to implement these two interface, you should override afterPropertiesSet() and destroy() method as below.

public class InitAndDestroyByInterface implements InitializingBean, DisposableBean {

	@Override
	public void destroy() throws Exception {

		System.out.println("This is the destroy() method which will be invoked just before this bean's destruction. ");

	}

	@Override
	public void afterPropertiesSet() throws Exception {
		
		System.out.println("This is the afterPropertiesSet() method which will be invoked right after this bean's initialization. ");

	}
	
	public static void main(String[] args) {
	   	// Initiate Spring application context, this line code will invoke bean initialize method.
		ApplicationContext springAppContext = new ClassPathXmlApplicationContext("BeanSettings.xml");

		// Get InitAndDestroyByAnnotation by id. 
		InitAndDestroyByInterface exampleBean = (InitAndDestroyByInterface) springAppContext.getBean("initAndDestroyByInterface");
		
		// Close spring context, this line of code will invoke the bean destroy methods.
		((ClassPathXmlApplicationContext) springAppContext).close(); 
	}

}

BeanSettings.xml

<bean id="initAndDestroyByInterface" name="initAndDestroyByInterface" 
    class="com.dev2qa.example.spring.bean.initdestroy.InitAndDestroyByInterface"> 
</bean>

Output

spring bean init and destroy by interface output

4. Execution order about above methods.

Now there are three spring beans that use different method to make it’s initialization and destruction, if you add all these beans in bean configuration file and run, you can see below output.

spring bean init and destroy method run order

You can see the int method execution order is : @PostConstruct annotated init method,  bean init-method parameter defined method, implement InitializingBean method.

The destroy method execution order is : implement DisposableBean method, bean destroy-method parameter defined method, @PreDestroy annotated destroy method.

5. Global bean initialization and destruction method.

If you have a lot of bean use the same init and destroy method, you can make them to use one global init and destroy method declared in beans tag like below. The default-init-method and default-destroy-method parameter value is just the method name.

<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:p="http://www.springframework.org/schema/p" 
       xmlns:context="http://www.springframework.org/schema/context" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd" 
       default-init-method="globalInit" default-destroy-method="globalDestroy" >
       
       <bean id="initAndDestroyGlobal" name="initAndDestroyGlobal" 
             class="com.dev2qa.example.spring.bean.initdestroy.InitAndDestroyGlobal"> 
       </bean>
</beans>

After declaration, you should create a bean with method globalInit and globalDestroy.

public class InitAndDestroyGlobal {

	public void globalInit()
	{
		System.out.println("This is the globalInit() method. ");
	}
	
	public void globalDestroy()
	{
		System.out.println("This is the globalDestroy() method. ");
	}
}

Now run any of java class in this example, you can see the global init method will be invoked at last and global destroy method will be invoked at first.

READ :   How To Install Spring IDE Eclipse Plugin

global init and destroy method output

Download “SpringBeanInitializeAndDestroyExamples-1.zip” SpringBeanInitializeAndDestroyExamples-1.zip – Downloaded 46 times – 3 KB

(Visited 741 times, 8 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.