10

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 Answers 3

6

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

1
  • @a-Learner Try adding adding debug points in your class Constructor. When you start app for debugging, you will see that the debug point is hit as many times as you have beans of that class.
    – rk2010
    Oct 16, 2012 at 15:56
0

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.