Reputation: 13153
Suppose have following beach definition:
<bean id="singletonBean" class="...">
<property name="instanceBean" ref="instanceBean"/>
</bean>
<bean id="instanceBean" class="..." scope="prototype"/>
When I call:
singletonBean = context.getBean("singletonBean");
...some code...
singletonBean = context.getBean("singletonBean");
Would property instanceBean
of singletonBean
be initialized again or it would just use already created singleton?
Upvotes: 2
Views: 3234
Reputation: 3625
When invoked context.getBean("singletonBean")
always it contains the same instance of instanceBean
, though the scope is prototype
in the bean definition.
On the contrary if the container bean is of scope prototype
and it refers to a bean which is defined with scope singleton
, always the inner bean would be singleton. Eg:-
<bean id="outer" class="OuterBean" scope="prototype">
<property name="innerBean" ref="inner" />
</bean>
<bean id="inner" class="InnerBean" scope="singleton"/>
OuterBean outer1 = (OuterBean) context.getBean("outer");
OuterBean outer2 = (OuterBean) context.getBean("outer");
Here both outer1
and outer2
will contain same instance of InnerBean
.
In a multitheaded environment, if innerBean
holds any shared data, it can lead to race condition.
Upvotes: 0
Reputation: 9862
Would just use already created singleton.
A prototyped inner bean of a singleton won't be recreated each time you get the singleton from context. The singleton and all is references are created one for all.
But context.getBean("instanceBean");
would give you a new since scope is 'prototype'.
Upvotes: 4
Reputation: 9440
instanceBean is set only once on startup, so you can get the instanceBean
by singletonBean.getInstanceBean()
if you like.
Upvotes: 0