Spring Bean Scope

In this article, we will discuss about various bean scopes provided by Spring Framework or to be precise Spring IOC container. When you define your beans in configuration file, it actually tells the container about how to create and manage these beans at runtime. Various bean scopes supported are

  • singleton
  • prototype
  • request
  • session
  • global-session

Let’s expand them each one in detail.

Bean Scopes in Spring

Bean Scope Explanation
singleton Default
Returns single bean instance per IOC container
prototype Returns new bean instance each time requested.
request Returns single bean instance per HTTP request.
Every new HTTP request will get new bean instance assigned and on completion bean will be out of scope and available for GC.
session Returns single bean instance per HTTP session.
global- session Returns single bean instance per HTTP global session.

Note: Mostly we will deal with Spring’s core scope – singleton & prototype, whereas other three scope viz.; request, session & global-session are valid in the context of web aware Spring ApplicationContext like WebXmlApplicationContext

Let’s us dig deep into the code for spring’s core scopes – singleton & prototype

 

Technology Used

  • Java 1.7
  • Eclipse Kepler
  • Maven 3.0.4
  • Spring-4.0.0-RELEASE

Mavenize or download required jars

Add Spring-4.0.0 dependencies to the pom.xml

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

Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the spring site and include them in the classpath.

  • spring-core-4.0.0-RELEASE
  • spring-context-4.0.0-RELEASE
  • spring-beans-4.0.0-RELEASE
  • spring-aop-4.0.0-RELEASE
  • spring-expression-4.0.0-RELEASE
  • commons-logging-1.1.1
  • aopalliance-1.0

1. Singleton Example

 

Create simple Spring bean for Employee

Employee class

Simple Spring with two basic member variables and their corresponding setter/getter

Employee.java

package com.spring.series.bean.scope;

public class Employee {

	// member variables
	private String name;
	private String designation;

	// getter's & setter's
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDesignation() {
		return designation;
	}
	public void setDesignation(String designation) {
		this.designation = designation;
	}
}

Create Spring Bean Configuration file (Spring XML)

Spring Context xml contains one simple bean definition for employee with attribute scope=“singleton” set in the element <bean> tag. This is also default behavior of spring i.e.; even if you haven’t set this attribute by default it will returns same bean instance every time requested.

Note: omitting scope=“singleton” attribute from the <bean> tag has the same effect of the below configuration.

SpringContext.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-4.0.xsd">

	<!-- employee bean definition goes here -->
	<bean id="employee" class="com.spring.series.bean.scope.Employee"
		scope="singleton">
	</bean>

</beans>

Note: Name of the Spring Bean Configuration file can be anything (not necessary to have SpringContext.xml) and it’s your choice. But, in the enterprise application keep these file names appropriate to the business context. So that it will increase the readability of the application.

Project Structure in Eclipse (Package Explorer view)

SpringBeanScope

Test the Application that’s exactly …. Run it!

Let’s test using ApplicationContext

This test class uses the ApplicationContext superset of BeanFactory to load the Spring context file from the classpath

  • getBean(“employee”); api returns the single bean instance named employee1
  • Set the values of employee member variables (name/designation) using above returned employee1 instance
  • Print the values in the console output using employee1 bean
  • Again, retrieve the employee bean for another employee i.e.; emplopyee2 bean
  • Try to print the values in the console for employee2; it prints the same values as that of the employee1. (which actually set by employee1 bean)

TestEmployee.java

package com.spring.series.bean.scope;

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

public class TestEmployee {

	public static void main(String[] args) {
		testBeanScopes();
	}

	private static void testBeanScopes(){

		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/spring/series/bean/scope/SpringContext.xml");

		// employee 1 - retrieve employee bean
		Employee employee1 = (Employee) applicationContext.getBean("employee");

		// setting values using employee1 bean
		employee1.setName("Mark Anthony");
		employee1.setDesignation("Technical Architect");

		// print values in console using employee1 bean
		System.out.println("\nPrinting values in console using employee1 bean");
		System.out.println("Name \t\t: " + employee1.getName());
		System.out.println("Designation \t: " + employee1.getDesignation());

		// employee 2 - retrieve again the same bean
		Employee employee2 = (Employee) applicationContext.getBean("employee");

		// print values in console using employee1 bean
		System.out.println("\n\nPrinting values in console using employee2 bean");
		System.out.println("Name \t\t: " + employee2.getName());
		System.out.println("Designation \t: " + employee2.getDesignation());
	}
}

Output in console

Printing values in console using employee1 bean
Name 		: Mark Anthony
Designation 	: Technical Architect

Printing values in console using employee2 bean
Name 		: Mark Anthony
Designation 	: Technical Architect

 

2. Prototype Example

For prototype example, let’s keep everything same except tweaking some attribute in the SpringContext configuration file.

Change the attribute scope to scope=“prototype”from the above singleton example. Rest everything is same. Time to view output in the console

SpringContext.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-4.0.xsd">

	<!-- employee bean definition goes here -->
	<bean id="employee" class="com.spring.series.bean.scope.Employee"
		scope="prototype">
	</bean>

</beans>

Output in console

Printing values in console using employee1 bean
Name 		: Mark Anthony
Designation 	: Technical Architect

Printing values in console using employee2 bean
Name 		: null
Designation 	: null

Output in the console explains that, when second time bean is requested it returned a new instance instead of the same old instance as in the case of singleton scope. And prints ‘null’ for member variables name/designation for the employee2 bean

Conclusion: Its a design choice and business requirement to choose one over other

Download project

Spring Bean Scope - Singleton (3kB)
Spring Bean Scope - Prototype (3kB)

Happy Coding !!
Happy Learning !!

Spring Annotation using @Autowired
Spring Autowiring using constructor