a Learner
a Learner

Reputation: 5042

spring singleton scope

Spring reference manual says:

The scope of the Spring singleton is best described as "per container and per bean".

consider this code snippet:

ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml")
MyBean myobj=(MyBean)context.getBean("myBean"); //myBean is of singleton scope.
MyBean myobj1=(MyBean)context.getBean("myBean");

per container means that if we do context.getBean("myBean"); twice it will return same bean i.e. myobj==myobj1 is true.

But what does per bean in per container and per bean from above statement means?

Upvotes: 2

Views: 1263

Answers (3)

a Learner
a Learner

Reputation: 5042

I asked another question in reference to this one:spring singleton scope— per container per bean

From that I concluded following for per bean part of phrase per container per bean:

Consider:

ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml")
MyBean myobj=(MyBean)context.getBean("myBean"); 
MyBean myobj1=(MyBean)context.getBean("myBean"); 
MyBean myobj2=(MyBean)context.getBean("mySecondBean");

Beans.xml:

<bean id="myBean" class="MyBean"/>
<bean id="mySecondBean" class="MyBean"/>

Now Singleton in Spring is per container per bean.

per container means if we get same bean id by getBean() within same container then they represent same instances.Therefore myobj==myobj1 is true.

And if we get bean with same id in two different containers then they will represent two different instances.This is represented in answer above given by Nirmal- thInk beYond.

But for singleton, within per container it should also be per bean(per bean tag).

i.e if we define two beans in configuration file of same class then they represent different instances even within same container.

Thats why myobj==myobj2 is false.

Upvotes: 0

Nirmal- thInk beYond
Nirmal- thInk beYond

Reputation: 12054

in simple way

ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml")
MyBean myobj=(MyBean)context.getBean("myBean"); //myBean is of singleton scope.

ApplicationContext context1= new ClassPathXmlApplicationContext("Beans.xml")
MyBean myobj1=(MyBean)context1.getBean("myBean");

myobj==myobj1 would not be same

Upvotes: 4

Jigar Joshi
Jigar Joshi

Reputation: 240898

Spring bean container will create single bean for singleton scoped beans, if you have another container of spring the different bean would get created

so per container there would be single instance of bean (for singleton scoped beans)

Upvotes: 3

Related Questions