Spring beans with scope prototype
Suppose have following beach definition:
<bean id="singletonBean" c开发者_高级运维lass="...">
<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?
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'.
instanceBean is set only once on startup, so you can get the instanceBean
by singletonBean.getInstanceBean()
if you like.
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.
精彩评论