Spring Prototype Bean Scope Example (original) (raw)

In the spring framework, developers can create beans using the in-built spring bean scopes. Out of five in-built scopes, Singleton and Prototype are primary and available in any type of IOC containers. This tutorial will explore the Prototype bean that returns a new bean instance for each and every request.

1. Introduction

1.1 Spring Framework

1.2 Spring Bean Scopes

In the spring framework, the bean scope determines:

There are five types of bean scopes available and let’s briefly list down all of them.

Scope Effect
Singleton A single bean instance is created per IOC container and this is the default scope
Prototype A new bean instance is created each time the bean is requested from the IOC container
Request A single bean instance is created and available during the lifecycle of the HTTP request. Only valid with a web-aware spring ApplicationContext container
Session A single bean instance is created and available during the lifecycle of the HTTP session. Only valid with a web-aware spring ApplicationContext container
Global-Session A single bean instance is created and available during the lifecycle of the global HTTP session (i.e. for portlet environments). Only valid with a web-aware spring ApplicationContext container

1.2.1 Spring Prototype Bean Scope

Prototype scope in the spring framework creates a new instance of a bean, every time; a request for that specific bean is made. The Prototype scope is preferred for the stateful beans, and the spring container does not manage the complete lifecycle of a prototype bean i.e. destruction lifecycle methods are uncalled. Like so, a developer is responsible for cleaning up the prototype-scoped bean instances and any resources it holds. Below snippet shows how to specify the prototype scope bean in the configuration file.

Code Snippet

But developers can define the scope of a bean using the @Scope(value= ConfigurableBeanFactory.SCOPE_PROTOTYPE) annotation. Below snippet shows how to specify the prototype scope bean using the Java configuration.

Code Snippet

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

......

}

Always remember, to use the Prototype scope for the stateful beans and the Singleton scope for the stateless beans. Now, open up the Eclipse IDE and let us see how to create a prototype bean using the xml-based configuration in the spring framework.

Here is a systematic guide for implementing this tutorial in the spring framework.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Spring Prototype Bean Scope - Application Project Structure

Fig. 1: Application Project Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring Prototype Bean Scope - Create a Maven Project

Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Spring Prototype Bean Scope - Project Details

Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Spring Prototype Bean Scope - Archetype Parameters

Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

4.0.0 com.spring SpringPrototypeScope 0.0.1-SNAPSHOT jar

We can start adding the dependencies that developers want like Spring Core, Spring Context etc. Let us start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the spring framework. Maven will automatically resolve the rest dependencies such as Spring Beans, Spring Core etc. The updated file will have the following code:

pom.xml

4.0.0 com.spring SpringPrototypeScope 0.0.1-SNAPSHOT org.springframework spring-beans 5.0.8.RELEASE org.springframework spring-context 5.0.8.RELEASE ${project.artifactId}

3.2 Java Class Creation

Let us write the Java classes involved in this application.

3.2.1 Implementation of Model class

The model class contains two fields for demonstrating the use of prototype bean scope. Add the following code to it:

Message.java

package com.spring.model;

public class Message {

private int id;
private String message;

public Message() {
    System.out.println("Prototype Bean Instantiated ...!!");
}

public int getId() {
    return id;
}

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

public String getMessage() {
    return message;
}

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

@Override
public String toString() {
    return "Message [Id= " + id + ", Message= " + message + "]";
}

}

3.2.2 Implementation of Utility class

The configuration class defines the bean definition for the model class. Add the following code to it:

AppConfig.java

package com.spring;

import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.model.Message;

public class AppMain {

public static void main(String[] args) {

    ApplicationContext ac = new ClassPathXmlApplicationContext("prototype-bean.xml");

    Message message1 = ac.getBean("messageServ", Message.class);

    // Setting the object properties.
    message1.setId(1001);
    message1.setMessage("Hello world!");

    System.out.println(message1.toString());

    // Retrieve it again.
    Message message2 = ac.getBean("messageServ", Message.class);
    System.out.println(message2.toString());

    // Closing the context object.
    ((AbstractApplicationContext)ac).close();
}

}

3.3 Configuration Files

Following is the bean configuration file required for the prototype scope. A typical bean configuration file will look like this:

prototype-bean.xml

<!-- Setting the bean scope to 'Prototype' -->
<bean id="messageServ" class="com.spring.model.Message" scope="prototype" />

4. Run the Application

To execute the application, right click on the AppMain class, Run As -> Java Application. Developers can debug the example and see what happens after every step. Enjoy!

Spring Prototype Bean Scope - Run the Application

Fig. 5: Run the Application

5. Project Demo

The code shows the following logs as follows.

Logs

INFO: Loading XML bean definitions from class path resource [prototype-bean.xml]

Prototype Bean Instantiated ...!! Message [Id= 1001, Message= Hello world!]

Prototype Bean Instantiated ...!! Message [Id= 0, Message= null]

Sep 26, 2018 9:00:32 PM org.springframework.context.support.AbstractApplicationContext doClose

The output shows that when the second time the message2 bean is requested, it returns a new instance instead of the old instance as in the case of singleton scope. Therefore, a null value is printed for the member variables of the message2 bean.

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

This post defines the different bean scopes provided by the spring framework and how to effectively use and manage the prototype scope in a spring application.

Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of a prototype bean scope in the spring framework.

Download
You can download the full source code of this example here: SpringPrototypeScope

Photo of Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).