registerShutdownHook() Spring Example
February 10, 2013
In spring, registerShutdownHook() method is used to shut down IoC container in non-web applications. It shuts down IoC container gracefully. In non web based application like desk top application it is required to call registerShutdownHook. In our desktop application we need to release all resources used by our spring application. So we need to ensure that after application is finished, destroy method on our beans should be called. In web-based application ApplicationContext already implements code to shut down the IoC container properly. But in desktop application we need to call registerShutdownHook to shutdown IoC container properly.
Using registerShutdownHook() Method
Using the instance ofAbstractApplicationContext
, we call registerShutdownHook()
.
SpringDemo.java
package com.concretepage; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringDemo { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); Animal animal = (Animal)context.getBean("animal"); System.out.println("Animal Name:"+ animal.getAnimalName()); context.registerShutdownHook(); } }
Declare Bean
spring-config.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="animal" class="com.concretepage.Animal" destroy-method="preDestroy"> <constructor-arg name="animalName" value="Elephant"/> </bean> </beans>
Animal.java
package com.concretepage; public class Animal { private String animalName; public Animal(String animalName) { this.animalName = animalName; } public String getAnimalName() { return animalName; } public void preDestroy() { System.out.println("---Release resources or perform destruction task---"); } }
Output
When we runSpringDemo
class, we can observe in output that after calling registerShutdownHook()
, the custom destroy method as preDestroy()
is called.
Animal Name:Elephant ---Release resources or perform destruction task---