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?
I asked another question in reference to this one:spring singleton scope— per container per bean
From that I concluded following for
per beanpart of phraseper container per bean:Consider:
Beans.xml:
Now Singleton in Spring is
per container per bean.per containermeans if we get same bean id bygetBean()within same container then they represent same instances.Thereforemyobj==myobj1is 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 containerit should also beper 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==myobj2is false.