Ebooks

Spring Prototype scope bean

Spring Prototype scoped bean tutorial shows how to use a Prototype scoped bean in a Spring application.

Spring is a popular Java application framework for creating enterprise applications.

Spring Prototype bean

Prototype beans are created every time a new request for that bean is made.

Other bean scopes are: singleton, request, session, global session, and application.

Spring Prototype bean example

The application creates two prototype scoped beans and checks if they are identical. The application is a classic Spring 5 console application.

────src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           │
│   │           └───bean
│   │                   Message.java
│   │
│   └───resources
│           logback.xml
│           my-beans.xml
│
└───test
    └───java

This is the project structure.

pom.xml
<?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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>prototypescopedbean</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <spring-version>5.1.3.RELEASE</spring-version>

    </properties>

    <dependencies>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-version}</version>
        </dependency>
        
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.6.0</version>
                <configuration>
                    <mainClass>com.zetcode.Application</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

In the pom.xml file, we have basic Spring dependencies spring-core and spring-context and logging logback-classic dependency.

The exec-maven-plugin is used for executing Spring application from the Maven on the command line.

resources/my-beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.zetcode"/>

</beans>

With the context:component-scan tag, we instruct Spring to look for beans in the com.zetcode package. It will find our sole Message bean, which is decorated with @Component.

resources/logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.zetcode" level="INFO"/>

    <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <Pattern>%d{HH:mm:ss.SSS} [%thread] %blue(%-5level) %magenta(%logger{36}) - %msg %n
            </Pattern>
        </encoder>
    </appender>

    <root>
        <level value="INFO" />
        <appender-ref ref="consoleAppender" />
    </root>
</configuration>

The logback.xml is a configuration file for the Logback logging library.

com/zetcode/bean/Message.java
package com.zetcode.bean;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class Message {

    private String message;

    public String getMessage() {

        return message;
    }
}

The Message is a Spring bean managed by the Spring container. It has prototype scope.

@Component
@Scope("prototype")
public class Message {

The @Scope("prototype") sets the scope of the bean to prototypes; the default is singleton.

com/zetcode/Application.java
package com.zetcode;

import com.zetcode.bean.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.GenericXmlApplicationContext;

public class Application {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {

        var ctx = new GenericXmlApplicationContext("my-beans.xml");

        var beanA = ctx.getBean(Message.class);
        var beanB = ctx.getBean(Message.class);

        if (beanA.equals(beanB)) {

            logger.info("The beans are identical");
        } else {

            logger.info("The beans are not identical");
        }

	ctx.close();
    }
}

This is the main application class.

var ctx = new GenericXmlApplicationContext("my-beans.xml");

We create the Spring application context from the my-beans.xml file using GenericXmlApplicationContext.

var bean1 = ctx.getBean(Message.class);
var bean2 = ctx.getBean(Message.class);

app.run(bean1, bean2);

We get two beans from the application context and pass them to the run() method for comparison.

logger.info(a.getMessage());

We read the message from the bean.

if (a.equals(b)) {

    logger.info("The beans are the same");
} else {

    logger.info("The beans are not the same");
}

We test if the two beans are identical.

$ mvn -q exec:java
21:26:03.089 [com.zetcode.Application.main()] INFO  com.zetcode.Application - The beans are not identical

We run the application. Change the spope of the Message bean to singleton and compare the results.

In this tutorial, we have worked with a prototype Spring bean.

You might also be interested in these related tutorials: JdbcTemplate in a classic Spring application, Spring Singleton scope bean, Spring ClassPathResource tutorial, Spring inject List XML tutorial, Spring BeanDefinitionBuilder tutorial, Spring HikariCP tutorial, and Java tutorial.