Home » Enterprise Java » spring » Spring Singleton Bean Scope Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Spring Singleton 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 Singleton bean that returns a single bean instance per IOC container.

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.

ScopeEffect
SingletonA single bean instance is created per IOC container and this is the default scope
PrototypeA new bean instance is created each time the bean is requested from the IOC container
RequestA single bean instance is created and available during the lifecycle of the HTTP request. Only valid with a web-aware spring ApplicationContext container
SessionA single bean instance is created and available during the lifecycle of the HTTP session. Only valid with a web-aware spring ApplicationContext container
Global-SessionA 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 Singleton Bean Scope

Singleton scope in the spring framework is the default bean scope in the IOC container. It tells the container to exactly create a single instance of the object. This single instance is stored in the cache and all the subsequent requests for that named bean return the cached instance. Below snippet shows how to specify the singleton scope bean in the configuration file.

Code Snippet

<!-- To specify singleton scope is redundant -->
<bean id="id" class="com.spring.model.Bean" scope="singleton" />

//or
<bean id="id" class="com.spring.model.Bean" />

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

Code Snippet

@Component
//This statement is redundant. Singleton is the default scope!
@Scope("singleton")
public class Bean {
 
	......
}

Always remember, if no bean scope is specified in the bean configuration file or by the @Scope annotation, then it will be singleton by default. Now, open up the Eclipse IDE and let us see how to create a singleton bean using the xml-based configuration in the spring framework.

2. Spring Singleton 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!

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

<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>SpringSingletonScope</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>SpringSingletonScope</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 singleton bean scope. Add the following code to it:

Message.java

package com.spring.model;

public class Message {

	private int id;
	private String message;

	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("singleton-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 singleton scope. Do note, if no bean scope is specified in the bean configuration file, it defaults to Singleton. A typical bean configuration file will look like this:

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

	<!-- Default Bean Scope In Spring Framework Is 'Singleton' -->
	<bean id="messageServ" class="com.spring.model.Message" />

	<!-- 
	<bean id="messageServ" class="com.spring.model.Message" scope="singleton" /> 
	-->
</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!

Spring Singleton 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 [singleton-bean.xml]

Message [Id= 1001, Message= Hello world!]
Message [Id= 1001, Message= Hello world!]

Since the messageServ bean is in singleton scope, the second fetch by the message2 object will display the details set by the message1 object, even if it is fetched by the new getBean() method.

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 singleton scope in a spring application.

  • In Singleton, only one instance per IOC container and this is the default scope in spring
  • For a singleton bean, the lifecycle of a bean is never impacted
  • It always returns the single instance for every fetch with the getBean() method
  • In Singleton, the bean instance is not thread-safe

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

7. Download the Eclipse Project

This was an example of Spring Singleton Bean Scope.

Download
You can download the full source code of this example here: SpringSingletonScope
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of