Spring Bean Scope

    0 Votes

When Spring beans are created by Spring containers, you can provide instructions to Spring bean by “scope” attribute about how this bean should be scoped.

Here Scope means, How many bean instances will be created for a certain context. In our application we create some classes as Singleton or some classes need to instantiate whenever client invoke it. Furthermore, in web application we want to create instances based on per request, per session, per context etc. Those are called the scope of a bean.

Spring has 5 scopes in which first two are used for Spring core and rest of the three are applicable for a Web application.
Diagram: Scopes of Spring bean

spring bean scope

As I said, Spring core only uses two scope - Singleton and prototype. Let us try to understand them by example.

Singleton Scope

Singleton scope says only one instance will be there in Spring container. Please note that the instance is in Spring container and not in JVM.

So if I change a property of a bean and again try to load the bean from the container, I should able to see that changes, since only one instance is maintained in the container.

Example:

BeanScope.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-3.0.xsd">

<bean id="bike" class="com.example.scope.Bike" scope="singleton">
<property name="name" value="HeroHonda"/>
</bean><> </beans>


Java Code

package com.example.scope;

public class Bike {
	
	private String name;

	public String getName() {
		return name;
	}

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

	@Override
	public String toString() {
		return "Bike [name=" + name + "]";
	}
}

package com.example.scope;

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

public class Application {
	
	public static void main(String[] args) 
	{
		ApplicationContext ctx = new ClassPathXmlApplicationContext("configFiles/BeanScope.xml");
	    
		Bike bike =(Bike) ctx.getBean("bike");
		System.out.println("Bike info ::" + bike);
		bike.setName("CBZ");
		System.out.println("Bike info After ::" + bike);
		Bike bike1 =(Bike) ctx.getBean("bike");
		System.out.println("Requesting container again  ::" + bike1);
		System.out.println("Both instance is same ? " + (bike==bike1));
	}
}

Output:

Bike info ::Bike [name=HeroHonda]
Bike info After ::Bike [name=CBZ]
Requesting container again ::Bike [name=CBZ]
Both instance is same ? true

Please note that in SpringBean.xml, we set the bean scope as the singleton. By doing so, we give an instruction to Spring container to make the Bike bean as Singleton.

Default scope of Spring bean is Singleton, so either we define or omit scope property. Spring always creates a singleton bean.

As Spring container manages only one instance of bike bean, after changing the name of the bike, that changed name is retained. If we make the request or bike bean once again, it will show the changed name not the name provide by configuration.

Let change the scope to prototype and see what will be the output.

Prototype Scope

Spring offers a new bean instance per invocation.

<?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-3.0.xsd"> <bean id="bike" class="com.example.scope.Bike" scope="prototype">
<property name="name" value="HeroHonda"/>
</bean>
</beans>
package com.example.scope;

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

public class Application {
	
	public static void main(String[] args) {
	 ApplicationContext ctx = new ClassPathXmlApplicationContext("configFiles/BeanScope.xml");
    
        Bike bike =(Bike) ctx.getBean("bike");
        System.out.println("Bike info ::" + bike);
        bike.setName("CBZ");
        System.out.println("Bike info After ::" + bike);
        Bike bike1 =(Bike) ctx.getBean("bike");
        System.out.println("Requesting container again  ::" + bike1);
 System.out.println("Both instance is same ? " + (bike==bike1));
	}
}

Output:

Bike info ::Bike [name=HeroHonda]
Bike info After ::Bike [name=CBZ]
Requesting container again ::Bike [name=HeroHonda]
Both instance is same ? false

Oops, the output is changed. Because, now bean scope is a prototype. So, every invocation spring bean offers a new bean. So it will offer a new bean when we try to get a bean from container second time. Pay attention to equality in last line in Application.java that will clear the Idea.

Popular Videos

communication

How to improve your Interview, Salary Negotiation, Communication & Presentation Skills.

Got a tip or Question?
Let us know

Related Articles

Spring Framework - Overview
Spring Architecture
Step by step guide for Spring configuration
Building First Spring application
Spring Bean XML File
Spring Container
Spring Bean - Learn with an Example
Spring Bean Life Cycle
Spring Bean Post Processor
Spring Inner Bean
Spring Autowiring
Spring Autowiring Types
Spring Qualifier with Autowiring
Spring Collection Injection
Spring Inheritance
Spring Event Handling
Dependency Injection
Spring AOP
Spring AOP Example