Spring bean scopes

The scope of a bean specifies what kind of object has to be created by container for the bean defined.

We can define the scope of the bean while defining the bean in the spring configuration file.

Spring provides 5 scopes for a bean out of the box, we can also customize and create custom scope.

Types of bean scopes supported by Spring out of the box are as below

1. Singleton

Return a single bean instance per Spring container

2. Prototype

Return a new bean instance each time when requested for the container

3. Request

Return a single bean instance per HTTP request and Only valid in the context of a web-aware Spring ApplicationContext which means only in the web application.

4. Session

Return a single bean instance per HTTP session and Only valid in the context of a web-aware Spring ApplicationContext which means only in the web application.

5. GlobalSession

Return a single bean instance per global HTTP session
In portlet applications, session scope is considered as global session scope.
Hence only valid when used in a portlet context

Note:

By default, all the beans defined in spring will have singleton scope.

Singleton scope of a bean

As explained above, singleton bean will be only one instance for entire spring container, no matter how many times and in how many places we access it using context.getBean() method.

If we didn’t add any scope for the bean ,then Spring automatically makes that bean as Singleton.

Now Let us see Singleton bean with example


Create a class called Person as below

  1. package com.kb.beans.scope;
  2.  
  3. public class Person {
  4.    
  5.     private String name;
  6.    
  7.  
  8.     public String getName() {
  9.         return name;
  10.     }
  11.  
  12.     public void setName(String name) {
  13.         this.name = name;
  14.     }
  15.  
  16. }
package com.kb.beans.scope;

public class Person {
	
	private String name;
	

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}


Define the Person bean in the spring configuration file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  4.     xmlns:p="http://www.springframework.org/schema/p"
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  6.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  7.        http://www.springframework.org/schema/context
  8.         http://www.springframework.org/schema/context/spring-context-3.2.xsd">
  9.    
  10.     <bean id="person"  class="com.kb.beans.scope.Person">
  11.     <property name="name" value="Name1"/>
  12.     </bean>
  13. </beans>
<?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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
  		http://www.springframework.org/schema/context/spring-context-3.2.xsd">
	
	<bean id="person"  class="com.kb.beans.scope.Person">
	<property name="name" value="Name1"/>
	</bean>
</beans>

Note that,we have not defined any scope for the bean person in the above file,Even though the scope of a bean is Singleton because its default scope of a bean.

Create pom.xml as below

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.  
  5.   <groupId>Spring</groupId>
  6.   <artifactId>SpringCore</artifactId>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <packaging>jar</packaging>
  9.  
  10.   <name>SpringCore</name>
  11.   <url>http://maven.apache.org</url>
  12.  
  13.   <properties>
  14.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15.   </properties>
  16.  
  17.   <dependencies>
  18.   <dependency>
  19.     <groupId>org.springframework</groupId>
  20.     <artifactId>spring-core</artifactId>
  21.     <version>4.2.4.RELEASE</version>
  22. </dependency>
  23.   <dependency>
  24.     <groupId>org.springframework</groupId>
  25.     <artifactId>spring-context</artifactId>
  26.     <version>4.2.4.RELEASE</version>
  27. </dependency>
  28.  
  29.     <dependency>
  30.       <groupId>junit</groupId>
  31.       <artifactId>junit</artifactId>
  32.       <version>3.8.1</version>
  33.       <scope>test</scope>
  34.     </dependency>
  35.   </dependencies>
  36. </project>
<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>Spring</groupId>
  <artifactId>SpringCore</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>SpringCore</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  <dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<version>4.2.4.RELEASE</version>
</dependency>
  <dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>4.2.4.RELEASE</version>
</dependency>
  
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


Let us test the same in the below class

  1. package com.kb.beans.scope;
  2.  
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4.  
  5. public class BeanScopeTest {
  6.    
  7.     public static void main(String[] args) {
  8.        
  9.         ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
  10.  
  11.         // Load Person object
  12.         Person person1 = (Person) applicationContext.getBean("person");
  13.         System.out.println("Name : " + person1.getName());
  14.        
  15.         Person person2 = (Person) applicationContext.getBean("person");
  16.  
  17. System.out.println(person1 == person2);
  18.  
  19.         applicationContext.registerShutdownHook();
  20.  
  21.     }
  22. }
package com.kb.beans.scope;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanScopeTest {
	
	public static void main(String[] args) {
		
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

		// Load Person object
		Person person1 = (Person) applicationContext.getBean("person");
		System.out.println("Name : " + person1.getName());
		
		Person person2 = (Person) applicationContext.getBean("person");

System.out.println(person1 == person2);

		applicationContext.registerShutdownHook();

	}
}


Run the above class and see the output

Even though we have accessed the bean 2 times using getBean() method. We can see that 2 instances are same.

When we compare 2 instances using == , it always checks the memory location of the 2 objects, and it is returning true which means both are same objects.

Now let’s modify the above program as below

  1. package com.kb.beans.scope;
  2.  
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4.  
  5. public class BeanScopeTest {
  6.    
  7.     public static void main(String[] args) {
  8.        
  9.         ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
  10.  
  11.         // Load Person object
  12.         Person person1 = (Person) applicationContext.getBean("person");
  13.        
  14.         person1.setName("Name2");
  15.        
  16.         System.out.println("Name : " + person1.getName());
  17.        
  18.         Person person2 = (Person) applicationContext.getBean("person");
  19.        
  20.         System.out.println("Name : " + person2.getName());
  21.        
  22.         System.out.println(person1 == person2);
  23.  
  24.         applicationContext.registerShutdownHook();
  25.  
  26.    
  27.     }
  28.  
  29. }
package com.kb.beans.scope;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanScopeTest {
	
	public static void main(String[] args) {
		
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

		// Load Person object
		Person person1 = (Person) applicationContext.getBean("person");
		
		person1.setName("Name2");
		
		System.out.println("Name : " + person1.getName());
		
		Person person2 = (Person) applicationContext.getBean("person");
		
		System.out.println("Name : " + person2.getName());
		
		System.out.println(person1 == person2);

		applicationContext.registerShutdownHook();

	
	}

}

Here we have modified the person1 object to have a new name Name2
And loading person2 then accessing its name.

Now person2 also has a new name Name2 even though we have modified only person1

It clearly says that, both are one and the same instance.

Prototype scope of a bean

Prototype scope means container creates new instance every time we ask container to provide the bean using getBean() method.
Prototype scope must be defined explicitly

In simple words, each context.getBean() method returns a new object.

Now Let us see Prototype bean with example


Create a class called User as below

  1. package com.kb.beans.scope;
  2.  
  3. public class User {
  4.     private String name;
  5.  
  6.     public String getName() {
  7.         return name;
  8.     }
  9.  
  10.     public void setName(String name) {
  11.         this.name = name;
  12.     }
  13.  
  14. }
package com.kb.beans.scope;

public class User {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}


Define the bean and make it as prototype explicitly

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  4.     xmlns:p="http://www.springframework.org/schema/p"
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  6.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  7.        http://www.springframework.org/schema/context
  8.         http://www.springframework.org/schema/context/spring-context-3.2.xsd">
  9.    
  10.     <bean id="person"  class="com.kb.beans.scope.Person">
  11.     <property name="name" value="Name1"/>
  12.     </bean>
  13.    
  14.     <bean id="user"  class="com.kb.beans.scope.User" scope="prototype">
  15.     <property name="name" value="Name1"/>
  16.     </bean>
  17.    
  18. </beans>
<?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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
  		http://www.springframework.org/schema/context/spring-context-3.2.xsd">
	
	<bean id="person"  class="com.kb.beans.scope.Person">
	<property name="name" value="Name1"/>
	</bean>
	
	<bean id="user"  class="com.kb.beans.scope.User" scope="prototype">
	<property name="name" value="Name1"/>
	</bean>
	
</beans>


Now try to access the bean customer from the test class

  1. package com.kb.beans.scope;
  2.  
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4.  
  5. public class BeanScopeTest {
  6.    
  7.     public static void main(String[] args) {
  8.        
  9.         ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
  10.  
  11.        
  12.         // prototype
  13.        
  14.         User user1 = (User) applicationContext.getBean("user");
  15.        
  16.         user1.setName("Name2");
  17.        
  18.         System.out.println("Name : " + user1.getName());
  19.        
  20.        
  21.        
  22.         User user2 = (User) applicationContext.getBean("user");
  23.        
  24.         System.out.println("Name : " + user2.getName());
  25.        
  26.         System.out.println(user1 == user2);
  27.  
  28.         applicationContext.registerShutdownHook();
  29.  
  30.    
  31.     }
  32.  
  33. }
package com.kb.beans.scope;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanScopeTest {
	
	public static void main(String[] args) {
		
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

		
		// prototype
		
		User user1 = (User) applicationContext.getBean("user");
		
		user1.setName("Name2");
		
		System.out.println("Name : " + user1.getName());
		
		
		
		User user2 = (User) applicationContext.getBean("user");
		
		System.out.println("Name : " + user2.getName());
		
		System.out.println(user1 == user2);

		applicationContext.registerShutdownHook();

	
	}

}


Run the above program and see the output

Here we got the bean user1 by calling getBean() method

We changed its name to Name2 and then we accessed the bean user2 by calling getBean() method and its name is printed.

Note that, user2 has no affect of new Name this is because , the scope of User bean is set to prototype.

Also we compared user1 and user2 using == and it displayed as false, which means both are different objects.

So prototype scope always ensures that, each getBean() invocation returns the new object.

Download this project BeanScopes.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on