Spring Prototype Bean Scope Example
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
- Spring is an open-source framework created to address the complexity of an enterprise application development
- One of the chief advantages of the Spring framework is its layered architecture, which allows the developer to be selective about which of its components they can use while providing a cohesive framework for
J2EE
application development - Spring framework provides support and integration to various technologies for e.g.:
- Support for Transaction Management
- Support for interaction with the different databases
- Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
- Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
- Support for
REST
style web-services
1.2 Spring Bean Scopes
In the spring framework, the bean scope determines:
- Which type of bean instance should be returned from the spring container
- When the bean will come into existence and how long it stays in the spring container
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
<!-- Setting the bean scope to 'Prototype' --> <bean id="id" class="com.spring.model.Bean" scope="prototype" />
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.
2. Spring Prototype Bean Scope Example
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!
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
.
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.
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
.
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
<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.spring</groupId> <artifactId>SpringPrototypeScope</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> </project>
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
<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.spring</groupId> <artifactId>SpringPrototypeScope</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.0.8.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.8.RELEASE</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> </build> </project>
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
<?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"> <!-- Setting the bean scope to 'Prototype' --> <bean id="messageServ" class="com.spring.model.Message" scope="prototype" /> </beans>
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!
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.
- In prototype, a new bean instance is created for each
getBean()
method call - For a prototype bean, the destruction lifecycle methods are never called
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.
You can download the full source code of this example here: SpringPrototypeScope
too old style , but anyways, thanks for the post