How do I initialize and destroy beans in Spring?

When creating an instance of a bean you might need to do some initialization to the bean. Likewise, when the bean is no longer needed and removed from the Spring container you might want to do some cleanup routine or destroy the bean.

To do this initialization and destroy routine you can use the init-method and destroy-method attribute when declaring a bean in spring configuration using the <bean> element.

By defining the init-method and destroy-method it will allow the Spring Container to call the initialization method right after the bean created. And just before the bean removed and discarded from the container, the defined destroy method will be called. Let’s see some code snippet as an example.

package org.kodejava.spring.core;

public class AutoEngine {
    public void initialize() {
        System.out.println("AutoEngine.initialize");
    }

    public void destroy() {
        System.out.println("AutoEngine.destroy");
    }
}

Below is the Spring configuration file that where we register the bean. You’ll see in the configuration there are additional attributes that we add to the bean.

<?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="engine" class="org.kodejava.spring.core.AutoEngine" init-method="initialize" destroy-method="destroy" />

</beans>

Create a small program to execute our demo:

package org.kodejava.spring.core;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class InitDestroyDemo {
    public static void main(String[] args) {
        ConfigurableApplicationContext context =
                new ClassPathXmlApplicationContext("init-destroy.xml");

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

        // context.close will remove the bean from the container. 
        // This will call our bean destroy method.
        context.close();
    }
}

When you run the program it will print the following output:

AutoEngine.initialize
AutoEngine.destroy

The advantage of using this method to initialize or clean up the bean is that it does not mandate our bean to implement or extend any Spring API which will make our bean reusable on other container beside Spring.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I define bean scoping in Spring?

Bean scoping is how the bean is created and returned from the spring container to the bean requester. By default, the scope of all bean is singleton. The spring container will always return the same bean whenever this bean is required, for instance when in injected or call using the getBean() method from the application context.

There are five types of bean scope define in the Spring Container:

Scope Description
singleton Scope the bean definition to a single bean instance per Spring Container. This is the default scope when no scope is defined when creating a bean.
prototype Scope the bean to allow multiple times bean creation. This will create a new bean for each time the bean is required.
request Scope the bean definition to a single HTTP request. *
session Scope the bean definition to a single HTTP session. *
global-session Scope the bean definition to a global HTTP session. *

*) This is only valid when using the web-capable Spring context.

Let’s see the difference between Singleton and Prototype scope. First we’ll create our DummyService class.

package org.kodejava.spring.core;

public class DummyService {
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

Singleton Scope

By default, when no scope defined it will be a singleton.

<?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="service" class="org.kodejava.spring.core.DummyService" />

</beans>

Now create a program to run our example. First will run it using the singleton.xml as the configuration.

package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanScopeDemo {
    public static void main(String[] args) {
        try (var context = new ClassPathXmlApplicationContext("singleton.xml")) {
            DummyService serviceA = (DummyService) context.getBean("service");
            serviceA.setMessage("Hello From A");
            System.out.println("Message A = " + serviceA.getMessage());

            DummyService serviceB = (DummyService) context.getBean("service");
            System.out.println("Message B = " + serviceB.getMessage());
        }
    }
}

The output of the singleton configuration is:

Message A = Hello From A
Message B = Hello From A

The above output show that the message printed by the serviceB is the same as the serviceA. We don’t even set the message in the serviceB explicitly. It prints the same message because the getBean() method actually return the same bean both for serviceA and serviceB. This is the singleton scope.

Prototype Scope

To change the scope to prototype use the scope attribute in the bean element as shown below.

<?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="service" class="org.kodejava.spring.core.DummyService" scope="prototype" />

</beans>
package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanScopePrototypeDemo {
    public static void main(String[] args) {
        try (var context = new ClassPathXmlApplicationContext("prototype.xml")) {
            DummyService serviceA = (DummyService) context.getBean("service");
            serviceA.setMessage("Hello From A");
            System.out.println("Message A = " + serviceA.getMessage());

            DummyService serviceB = (DummyService) context.getBean("service");
            System.out.println("Message B = " + serviceB.getMessage());
        }
    }
}

Now if you try to run the same program again but changing the configuration to prototype.xml you’ll get the following output printed:

Message A = Hello From A
Message B = null

The serviceB now print a different message. This is the effect of using the prototype scope. When we call the getBean() a new bean will be created per request.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I inject a bean through constructors?

The following example demonstrate how we can inject a bean through their constructors. We will create a couple interfaces and classes for this purpose. First we will create the Singer interface and the Instrument interface. The Singer interface define a single method call sing() that will enable the implementation to sing a song.

The second interface, Instrument also define a single method call play(). This method will allow the implementation to play some instrument. After defining our example interface we create an implementation for each of them. The class will be called the AnySinger and Piano.

Here are the code that we have to code so far:

package org.kodejava.spring.core;

public interface Singer {
    /**
     * Sing a song.
     */
    void sing();
}
package org.kodejava.spring.core;

public interface Instrument {
    /**
     * Play an instrument.
     */
    void play();
}
package org.kodejava.spring.core;

public class AnySinger implements Singer {
    private String song = "Nana nana nana";
    private Instrument instrument = null;

    public AnySinger() {
    }

    /**
     * A constructor to create singer to sing a specific song.
     *
     * @param song the song title to sing.
     */
    public AnySinger(String song) {
        this.song = song;
    }

    /**
     * A constructor to create singer to sing a song while playing
     * an instrument.
     *
     * @param song       the song title to sing.
     * @param instrument the instrument to play.
     */
    public AnySinger(String song, Instrument instrument) {
        this.song = song;
        this.instrument = instrument;
    }

    @Override
    public void sing() {
        System.out.println("Singing " + song);
        if (instrument != null) {
            instrument.play();
        }
    }
}
package org.kodejava.spring.core;

public class Piano implements Instrument {

    @Override
    public void play() {
        System.out.println("Playing the Piano");
    }
}

We have created the classes that we need for our program to work. The next step is to create our spring configuration file. This will configure our bean in the spring container and wire all the dependency required by the bean.

<?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="piano" class="org.kodejava.spring.core.Piano" />

    <bean id="singer" class="org.kodejava.spring.core.AnySinger">
        <constructor-arg value="Dust in The Wind" />
        <constructor-arg ref="piano" />
    </bean>

</beans>

In the spring configuration we declare two beans. The first bean is the piano bean, which is a type of instrument. The main object of our example is the singer bean. To create the singer we use a constructor injector to inject some values or object reference for the bean to use.

In the singer bean we use the &lt;constructor-arg/&gt; element to inject dependency for the object. The value attribute can be use for passing a string or other primitive value. To pass an object reference we need to use the ref attribute.

Finally, we’ll create a simple program to run our constructed spring application. The code will include the process of loading our spring container, obtaining the bean from the container. Let’s see our singer in action.

package org.kodejava.spring.core;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

        Singer singer = (Singer) context.getBean("singer");
        singer.sing();
        context.close();
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I declare a bean in Spring application?

In this example we will learn how to declare a bean in Spring Application. We are going to build a simple Maven project to demonstrate it. So let’s begin by setting up our Maven project.

Creating a Maven Project

Below is the directory structure of our Maven Project.

.
├─ pom.xml
└─ src
   └─ main
      ├─ java
      │  └─ org
      │     └─ kodejava
      │        └─ spring
      │           └─ core
      │              ├─ Hello.java
      │              ├─ HelloImpl.java
      │              └─ HelloWorldDemo.java
      └─ resources
         └─ spring.xml

Configuring Maven pom.xml File

We need to create a pom.xml file and add our project configuration and library dependency.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>kodejava-example</artifactId>
        <groupId>org.kodejava</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>kodejava-springframework-core</artifactId>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.3.23</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.3.23</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.3.23</version>
        </dependency>
    </dependencies>
</project>

Creating a Bean

Next we will create a simple bean called HelloImpl. This bean implements an interface called Hello with a single method sayHello() to be implemented. Here is the interface it’s implementation definition.

package org.kodejava.spring.core;

public interface Hello {
    void sayHello();
}
package org.kodejava.spring.core;

public class HelloImpl implements Hello {

    public void sayHello() {
        System.out.println("Hello World!");
    }
}

Register the Bean in Spring Configuration

After having the bean we need to create the Spring configuration, which is an xml file, and we named it spring.xml. The bean declared using the bean element in the configuration file. At minimum the declaration contains the bean’s id and it’s class.

<?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="hello" class="org.kodejava.spring.core.HelloImpl" />

</beans>

Use the Bean in Our Application

Now we have the bean declared in the Spring container. The next step show you how to get the bean from the container and use it in our program. There are many ways that can be used to load the Spring container. Here we will use the ClassPathXmlApplicationContext. This class load the configuration that found in the runtime classpath.

package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloWorldDemo {
    public static void main(String[] args) {
        String config = "spring.xml";
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);

        Hello hello = (Hello) context.getBean("hello");
        hello.sayHello();
        context.close();
    }
}

How do I list property names of a Bean?

package org.kodejava.bean;

import java.io.Serializable;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.IntrospectionException;

public class Fruit implements Serializable {
    private Long id;
    private String name;
    private String latinName;
    private double price;

    public Fruit() {
    }

    public static void main(String[] args) {
        try {
            BeanInfo bi = Introspector.getBeanInfo(Fruit.class);
            PropertyDescriptor[] pds = bi.getPropertyDescriptors();

            for (PropertyDescriptor pd : pds) {
                String propertyName = pd.getName();

                System.out.println("propertyName = " + propertyName);
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLatinName() {
        return latinName;
    }

    public void setLatinName(String latinName) {
        this.latinName = latinName;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

The output of the code snippet above are:

propertyName = class
propertyName = id
propertyName = latinName
propertyName = name
propertyName = price