Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring singleton scope-- per container per bean

Tags:

java

spring

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?

like image 815
a Learner Avatar asked Oct 16 '12 15:10

a Learner


People also ask

How many bean scopes are specified in singleton by default?

singleton - only one instance of the spring bean will be created for the spring container. This is the default spring bean scope.

How does singleton bean serve multiple requests at the same time in Spring?

When the thread request the singleton bean, it is going to refer (with help of reference variable in stack) to the bytecode of singleton bean in heap. So multiple threads can refer singleton bean at the same time.

How many bean scopes are supported by Spring?

Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext ). Scopes a single bean definition to a single object instance per Spring IoC container.

What is the default scope of Bean * 1 point singleton prototype?

Explanation: Since the default scope is singleton, so items added by first bean instantiated will be used again by same bean if instantiated again. 8. In above question if scope of shoppingCart named bean is prototype, then what will be the output?


1 Answers

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

like image 165
rk2010 Avatar answered Sep 29 '22 11:09

rk2010