How do I defaulting init-method and destroy method in Spring?

When many beans in a context definition will have the same initialization and destroy method name, you can define a default-init-method and default-destroy-method in the attributes of the beans element.

This way you don’t have to define individual init-method and destroy-method for each of your beans. When the beans doesn’t supply the method that match the name of defined default-init-method or default-destroy-method nothing will happen to those beans.

Let’s see an example code below. Firs here is our simple bean, the AutoEngine bean.

package org.kodejava.example.spring;

public class AutoEngine {
    public void initialize() {

    public void destroy() {

And then we define our Spring configuration file. You can see that there are default-init-method and default-destroy-method in the attribute of the beans element.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <bean id="engine" class="org.kodejava.example.spring.AutoEngine"/>


And finally a small program to run our demo.

package org.kodejava.example.spring;

import org.springframework.context.ConfigurableApplicationContext;

public class DefaultInitDestroyDemo {
    public static void main(String[] args) {
        ConfigurableApplicationContext context =
                new ClassPathXmlApplicationContext("DefaultInitDestroy.xml");

        AutoEngine engine = (AutoEngine) context.getBean("engine");

        // context.close will remove the bean from the container.
        // This will call our bean destroy method.

When you run this example you’ll get the following output printed on your screen:

Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply