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"

    <bean class="com.memorynotfound.spring.core.lifecycle.Register"
        <constructor-arg name="name" value="Cache Register"/>


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");


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



You may also like...