10
votes

I am asking this Question in reference to my question:

spring singleton scope

Spring singleton is defined in reference manual as per container per bean.

per container means if we do like:

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

Beans.xml:

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

Then myobj==myobj1 will come out to true.Means both pointing to same instance.

For per bean part of phrase per container per bean i was somewhat confused. Am i right in following for per bean :

If we do like

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

Beans.xml:

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

Then myobj==myobj1 will come out to false. Means then they are two different instances?

3

3 Answers

6
votes

That is correct.

If it helps, you can also think of Spring beans as Instances that you would've otherwise created manually in your Java code using the constructor.

By defining the bean in the Spring XML file, that bean (Instance) gets registered with Spring's App Context and then that instance can be passed around to the other areas of the code.

By creating a new bean, you are effectively creating a new instance. So potentially you could create any number of beans (Instances) of the same class

0
votes

myBean is a Spring singleton in the sense of every call to beans.getBean("myBean") will allways return the same instance. And mySecondBeanhaving a different id is another Spring singleton. You can have different singleton beans of same class in the same ApplicationContext .

-1
votes

Yes, you're right. Testing it would have told you.