How do I define inner bean in Spring?

Inner bean is a bean defined inside another bean, it can be seen as an inner class. In another word, the inner bean is a bean defined within the scope of another bean. In this case the inner bean can only be use by the outer bean. No other bean in the Spring context can refer to that bean.

So, if you sure that a bean is only use within a single bean it is a good idea to use an inner bean. Inner bean can be injected through setter injection or constructor injection.

Here is an example of Spring configuration for an inner bean injection:

<?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="racer" class="org.kodejava.spring.core.Racer">
        <property name="car">
            <bean class="org.kodejava.spring.core.Car">
                <property name="maker" value="Ferrari" />
                <property name="year" value="2021" />
            </bean>
        </property>
    </bean>

</beans>

In this configuration we use a setter injection. So we use the property element. Instead of using a ref attribute for referring to another bean we define the bean using the bean element inside the property element. And then we create the Car bean and sets its properties.

If you want to use a constructor injection you can inject the Car bean into the Racer bean by defining a bean inside the constructor-arg element in the Racer bean.

Below is our Racer and Car classes.

package org.kodejava.spring.core;

public class Racer {
    private Car car;

    public Racer() {
    }

    public Racer(Car car) {
        this.car = car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    @Override
    public String toString() {
        return "Racer{" +
                "car=" + car +
                '}';
    }
}
package org.kodejava.spring.core;

public class Car {
    private String maker;
    private int year;

    public void setMaker(String maker) {
        this.maker = maker;
    }

    public void setYear(int year) {
        this.year = year;
    }

    @Override
    public String toString() {
        return "Car{" +
                "maker='" + maker + "'" +
                ", year=" + year +
                '}';
    }
}

Let’s create our Demo class to run the program:

package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo {
    public static void main(String[] args) {
        var context = new ClassPathXmlApplicationContext("inner-bean.xml");

        Racer racer = (Racer) context.getBean("racer");
        System.out.println("Racer = " + racer);
        context.close();
    }
}

Here is the output of our program:

Racer = Racer{car=Car{maker='Ferrari', year=2021}}

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 into bean properties?

A bean usually have some private properties that can be accessed through a pair of accessor methods, the setters and getters. These setters, the setXXX() method can be used by Spring Framework to configure the beans.

This method of injecting beans property through their setter methods is called the setter injection. The following example will show you how to do it.

Below is our DrawingBean that have colour and shape properties. In the example we will inject both of the properties using their respective setter method. The configuration is done in the Spring application configuration file.

package org.kodejava.spring.core;

public class DrawingBean {
    private String colour;
    private Shape shape;

    public DrawingBean() {
    }

    public void drawShape() {
        getShape().draw();
        System.out.printf("The colour is %s.", getColour());
    }

    public String getColour() {
        return colour;
    }

    public void setColour(String colour) {
        this.colour = colour;
    }

    public Shape getShape() {
        return shape;
    }

    public void setShape(Shape shape) {
        this.shape = shape;
    }
}

We can inject a simple value into a bean, such as string, number, etc. We can also inject a reference to another bean. Here we define an example of other bean, the Rectangle bean that we will inject into the DrawingBean.

package org.kodejava.spring.core;

public interface Shape {
    /**
     * Draw a shape.
     */
    void draw();
}
package org.kodejava.spring.core;

public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle.");
    }
}

Let’s create the Spring application configuration file that will register our beans into the Spring context. After that we just create a simple program to execute it.

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

    <bean id="drawingBean" class="org.kodejava.spring.core.DrawingBean">
        <property name="colour" value="Red" />
        <property name="shape" ref="rectangle" />
    </bean>

</beans>

In the configuration file above you can see that we use the property element to set a bean’s property. The name attribute is referring to the bean’s setter methods name, exclude the set prefix.

The value attribute of the property element is used to inject a simple value, such as string, int, etc. For injecting a reference to another bean we use the ref attribute instead.

package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DrawingBeanDemo {
    public static void main(String[] args) {
        try (var context = new ClassPathXmlApplicationContext("drawing-bean.xml")) {
            DrawingBean bean = (DrawingBean) context.getBean("drawingBean");
            bean.drawShape();
        }
    }
}

Here are the output of our example:

Drawing a rectangle.
The colour is Red.

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 create default 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 do not 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.spring.core;

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

    public void destroy() {
        System.out.println("AutoEngine.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="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"
       default-init-method="initialize" default-destroy-method="destroy">

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

</beans>

And finally a small program to run our demo.

package org.kodejava.spring.core;

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

public class DefaultInitDestroyDemo {
    public static void main(String[] args) {
        ConfigurableApplicationContext context =
                new ClassPathXmlApplicationContext("default-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 this example you’ll get the following output printed on your screen:

AutoEngine.initialize
AutoEngine.destroy

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 use InitializingBean and DisposableBean interfaces in Spring?

In the other example, How do I initialize and destroy beans in Spring? you can see how to initialize and destroy a bean using the Spring configuration init-method and destroy-method.

In the following example you’ll see how to achieve the same thing using the Spring API. In this case our class need to implements the InitializingBean and DisposableBean. These interfaces are located under the org.springframework.beans.factory package.

The InitializingBean interface requires us to implements the afterPropertiesSet() method. This method will be the init method of our bean. The destroy() method which is a contract defined in the DisposableBean interface is where we’ll place the clean-up logic of our bean.

The drawback of using this approach is that our classes will be required to use the Spring API. If you want to use the class outside the Spring container using the other approach mentioned above is a better way to go.

Now, let’s see some code in action.

package org.kodejava.spring.core;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class InitDisposeService implements InitializingBean, DisposableBean {

    /**
     * Do some processes.
     */
    public void doSomething() {
        System.out.println("InitDisposeService.doSomething");
    }

    /**
     * Initialize bean after property set.
     */
    @Override
    public void afterPropertiesSet() {
        System.out.println("InitDisposeService.afterPropertiesSet");
    }

    /**
     * Clean-up bean when the context is closed.
     */
    @Override
    public void destroy() {
        System.out.println("InitDisposeService.destroy");
    }
}

As usual, we define our Spring configuration (init-dispose.xml) to register our bean. In this case we will create a bean with id called service and will be using the InitDisposeService 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="service" class="org.kodejava.spring.core.InitDisposeService" />

</beans>

Below is a small Java program that we can use to run our application. This will load the Spring configuration, get the bean from the container and execute the bean. We’ll see that the afterPropertiesSet method is called. And when the context is closed the destroy method is also executed.

package org.kodejava.spring.core;

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

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

        InitDisposeService service =
                (InitDisposeService) context.getBean("service");
        service.doSomething();

        context.close();
    }
}

Here are the output printed on the screen:

InitDisposeService.afterPropertiesSet
InitDisposeService.doSomething
InitDisposeService.destroy

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 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