Bean scopes

spring Bean usually have one of the below scopes

1)singleton
2)prototype
3)request
4)session
5)global session

let me take first 2 scopes explanation in this post.

Singleton : only one instance of the bean will be created in the container.

ex: if Class A{
}
is a bean in spring like

<bean id="beanName" class ="A"/>

then

A a1= context.getBean("beanName"); A a2= context.getBean("beanName"); A a3= context.getBean("beanName");

all a1,a2 and a3 are same.

Prototype:each time we call context.getBean(“beanName”) , we will get new instance of that bean.

ex :in above example,we will get 3 objects a1,a2 and a3 all are different unlike Singleton.

Lets see with the code and output by taking Car as a example bean.

First create a Car class as below

package com.kb.beanscope;

import org.springframework.stereotype.Component;

@Component
public class Car {

	private String model;
	private String color;
	private double price;
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
}

now create a beans configuration file ie spring’s container of beans.

1
2
3
4
5
6
7
8
9
10
11
12
<?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-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
<context:component-scan base-package="com.kb.beanscope" />
</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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.kb.beanscope" />
</beans>

Now create a Client program which will try to access bean multiple times using context.getBean(“beanName”);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.kb.beanscope;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class MainClient {
    
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/kb/beanscope/beans.xml");
        Car car = (Car)applicationContext.getBean("car");
        car.setColor("blue");
        System.out.println(car.getColor());
        Car anottherCar = (Car)applicationContext.getBean("car");
        System.out.println(anottherCar.getColor());
    }
 
}
package com.kb.beanscope;

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

public class MainClient {
	
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/kb/beanscope/beans.xml");
		Car car = (Car)applicationContext.getBean("car");
		car.setColor("blue");
		System.out.println(car.getColor());
		Car anottherCar = (Car)applicationContext.getBean("car");
		System.out.println(anottherCar.getColor());
	}

}

Now run the program and see the output

even though we are calling context.getBean() 2 times, for second bean also the color set to first bean is coming,it clearly indicates this bean is singleton and yes by default all beans will be singleton.

even if we call context.getBean() 100 times we will get blue as output for that bean color.

2)Prototype: now modify the above program as below to make the bean as a prototype scope ,add @Scope(“prototype”)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.kb.beanscope;
 
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
 
@Component
@Scope("prototype")
public class Car {
 
    private String model;
    private String color;
    private double price;
    public String getModel() {
        return model;
    }
    public void setModel(String model) {
        this.model = model;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
}
package com.kb.beanscope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class Car {

	private String model;
	private String color;
	private double price;
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
}

and run our client program and see the output

so when we call context.getBean() 2 times, 2 instances of that bean got created as its scope is prototype.
so first bean color is coming as blue as we set it for first instance but for 2nd instance we haven’t set so coming as null. which clearly says 2 instances are created for the same bean.

if we call context.getBean() 100 times , 100 instances will be created.

Singleton Or Prototype ?

The lifecycle of beans is generally managed by the Spring container. But, when a bean is a prototype, Spring does not handle the destruction of the beans. means Spring does not call the destruction callback methods of prototype beans. we must write explicit code to clean up any prototype beans.
as Per the Spring documentation, “the Spring container’s role in regard to a prototype-scoped bean is a replacement for the Java new operator.
All lifecycle management past that point must be handled by the client.”

so prefer singleton unless there is a need for prototype in application.

About the Author

Karibasappa G C (KB)
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