Overview

When defining a <bean> you have the option of declaring scope for that bean

In this blog we will cover

  • What are different types of Scope available in Spring..
  • Example for each scope type

Types of Scope

Scope Description
singleton Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

singleton scope

  • When you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition.
  • This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.
  • The singleton scope is the default scope in Spring.
Sample
<bean id="accountService" class="com.foo.DefaultAccountService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default); using spring-beans-2.0.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/>

<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" singleton="true"/>
Example using 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">

	<!-- define the bean -->
  	<bean id="myPaint" class="com.main.spring.common.RedPaint" scope="singleton" ></bean>
  	
 </beans>

Paint Object

public interface Paint {
	public void getColor();
}

public class RedPaint implements Paint {

	public RedPaint() {
		System.out.println("RedPaint Constructor called");
	}
	
	@Override
	public void getColor() {
		System.out.println("I will paint Red color");
	}
}

Main class

public class MainApp {

	public static void main(String[] args) {

		// load the spring configuration file
		ClassPathXmlApplicationContext context = 
				new ClassPathXmlApplicationContext("scopeContext.xml");
			
		System.out.println("=========Checking Singelton Scope============");
		Paint paint = context.getBean("myPaint", Paint.class);
		Paint paint1 = context.getBean("myPaint", Paint.class);
		if(paint == paint1){
			System.out.println("Paint Pointing to same Object => "+paint+ " : "+paint1);
		}else{
			System.out.println("Paint Pointing to different Object => "+paint+ " : "+paint1);
		}
		context.close();
	}
}

OUTPUT:

RedPaint Constructor called
=========Checking Singelton Scope============
Paint Pointing to same Object => com.main.spring.common.RedPaint@7c29daf3 : com.main.spring.common.RedPaint@7c29daf3
Example using Annotation

add component scan in xml file

<context:component-scan base-package="com.main.spring.annotation"></context:component-scan>

Paint class

@Component
@Scope("singleton")
public class RedPaint implements Paint {

	@Override
	public void getColor() {
		System.out.println("I will paint Red color");
	}

	
}

Output

Paint Pointing to same Object => com.main.spring.common.RedPaint@7c29daf3 : com.main.spring.common.RedPaint@7c29daf3

The prototype scope

  • The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made you should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans.

Sample

<!-- using spring-beans-2.0.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/>

<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" singleton="false"/>

Example

Try same code we used for Singleton, just change scope as prototype like this

// For XML
<bean id="myPaint" class="com.main.spring.common.RedPaint" scope="prototype" ></bean>


// For Annotation 
@Component
@Scope("prototype")
public class RedPaint implements Paint {

	@Override
	public void getColor() {
		System.out.println("I will paint Red color");
	}
}



OUTPUT:

Paint Pointing to different Object => com.main.spring.common.RedPaint@7c29daf3 : com.main.spring.common.RedPaint@9660f4e

The other scopes (requestsession and global session)

  • The other scopes, namely request, session, and global session are for use only in web-based applications
  • In order to support the scoping of beans at the request, session, and global session levels (web-scoped beans), some minor initial configuration is required before you can set about defining your bean definitions.
  • If you are accessing scoped beans within Spring Web MVC, i.e. within a request that is processed by the Spring DispatcherServlet, or DispatcherPortlet, then no special setup is necessary: DispatcherServlet and DispatcherPortlet already expose all relevant state.
  • See here for more detail

You can get the code used above here. Just look for com.main.spring.scope package.

 

 

 


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.