Spring Bean Initialization And Destruction Examples

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

1. Methods To Customize Bean Post Initialization And Pre Destruction Behavior.

  1. Define bean with init() and destroy() methods in the 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.

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

  1. First, add the init-method and destroy-method properties in the bean definition file ( BeanSettings.xml ) as below.
    BeanSettings.xml

    <bean id="initAndDestroyExampleByConfiguration" name="initAndDestroyExampleByConfiguration" 
          init-method="postInitMethod" destroy-method="preDestroyMethod" 
          class="com.dev2qa.example.spring.bean.initdestroy.InitAndDestroyExampleByConfiguration"> 
    </bean>
  2. Second, implement the above method ( postInitMethod(),  preDestroyMethod() ) in the spring bean java file like below.
    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.
    This is bean post init method which will run immediately after initialization.
    
    hello
    
    This is bean pre destroy method which will run just before destroy.
    

3. Use @PostConstruct and @PreDestroy examples.

  1. You should add XML namespace context in the beans definition file, and add <context:annotation-config/> XML tag. Then you can define bean in it.
    <?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 java 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 when you run the above source code in eclipse.
    This is bean post init method annotated by @PostConstruct.
    
    Init and destroy use annotation.
    
    This is bean pre destroy method annotated by @PreDestroy.
    

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

  1. This is not the recommended method because it is highly coupled with the Spring framework. If you select to implement these two interfaces, you should override the 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(); 
    	}
    
    }
  2. BeanSettings.xml
    <bean id="initAndDestroyByInterface" name="initAndDestroyByInterface" 
        class="com.dev2qa.example.spring.bean.initdestroy.InitAndDestroyByInterface"> 
    </bean>
  3. Output.
    This is the afterPropertiesSet() method which will be invoked right after this bean's initialization.
    
    This is the destroy() method which will be invoked just before this bean's destruction.
    

5. Execution order about the above methods.

  1. Now there are three spring beans that use different methods to make it’s initialization and destruction, if you add all these beans in the bean configuration file and run, you can see the below output.
    This is bean post init method annotated by @PostConstruct.
    This is bean post init method which will run immediately after initialization.
    This is the afterPropertiesSet() method which will be invoked right after this bean's initialization.
    
    
    This is the destroy() method which will be invoked just before this bean's destruction.
    This is bean pre destroy method which will run just before destroy.
    This is bean pre destroy method annotated by @PreDestroy.
  2. You can see the int method execution order is: @PostConstruct annotated init method,  bean init-method parameter defined method, implement InitializingBean method.
  3. The destroy method execution order is: implement DisposableBean method, bean destroy-method parameter defined method, @PreDestroy annotated destroy method.

6. Global bean initialization and destruction method.

  1. If you have a lot of spring beans that use the same init and destroy method, you can make them use one global init and destroy method declared in the beans tag like below.
  2. The default-init-method and the default-destroy-method parameter value is just the related 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>
  3. After declaration, you should create a bean with methods 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. ");
    	}
    }
  4. Now run any of the java classes in this example, you can see the global init method will be invoked at last when initializing all the spring beans, and the global destroy method will be invoked at first when destroying all the spring beans.
    This is bean post init method annotated by @PostConstruct.
    This is bean post init method which will run immediately after initialization.
    This is the afterPropertiesSet() method which will be invoked right after this bean's initialization.
    
    This is the globalInit() method.
    
    Init and destroy use annotation.
    
    This is the destroy() method which will be invoked just before this bean's destruction.
    This is bean pre destroy method which will run just before destroy.
    This is bean pre destroy method annotated by @PreDestroy.
    

Leave a Comment

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.