Spring Lifecycle init-method and destroy-method
You can initialize or destroy your singleton bean using the xml configuration attributes init-method and destroy-method respectively. You must specify the name of the method that has a void no-argument signature. These methods will be called upon initialization and destruction of your singleton bean.
Initialization and Destruction Methods
It is a requirement that both init()
and destroy()
have a void no-argument method signature. They could also throw an exception, but in this example this is not the case.
package com.memorynotfound.spring.core.lifecycle;
public class Register {
private String name;
public Register(String name) {
this.name = name;
}
public void init(){
System.out.println("- - - initializing register bean using init-method");
System.out.println("Register name: " + name);
}
public void destroy(){
System.out.println("- - - destroying register bean using destroy-method");
}
}
Configure init-method and destroy-method
Using the spring xml configuration, we can configure the initalization and destruction methods using the init-method and destroy-method attributes of the <bean/> element respectively.
<?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 class="com.memorynotfound.spring.core.lifecycle.Register"
init-method="init"
destroy-method="destroy">
<constructor-arg name="name" value="Cache Register"/>
</bean>
</beans>
Registering the Shutdown Hook
The close();
method of the ConfigurableApplicationContext
will close the application context, release all the resources and destroy all cached singleton beans.
package com.memorynotfound.spring.core.lifecycle;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Run {
public static void main(String... args) throws InterruptedException {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("app-config.xml");
context.close();
}
}
Output
The init-method is called after the properties are set by spring container and the destroy-method is called before the JVM is closed.
- - - initializing register bean using init-method
Register name: Cache Register
- - - destroying register bean using destroy-method