registerShutdownHook() Spring Example
March 02, 2022
On this page we will learn using registerShutdownHook()
method.
1. The
registerShutdownHook()
is a method of Spring AbstractApplicationContext
class.
2. The
registerShutdownHook()
method registers a shutdown hook named SpringContextShutdownHook
with the JVM runtime. 3. On calling
registerShutdownHook()
, the Spring context is closed on JVM shutdown, if not already closed.
4. For actual context closing, the
registerShutdownHook()
delegates to doClose()
method of AbstractApplicationContext
class.
Using registerShutdownHook()
We callregisterShutdownHook()
method with the instance of AbstractApplicationContext
class.
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(); } }
XML Configuration
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>
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()
method, the custom destroy method as preDestroy()
is called.
Animal Name:Elephant ---Release resources or perform destruction task---