问题描述
我遇到Spring的问题:我需要重复使用相同的bean实例两次,但不要将它作为单例。
I have a problem with Spring: I need to reuse the same instance of bean twice, but not making it singleton.
这是一个简短的ApplicationContext:
Here is a brief ApplicationContext:
<bean class="a.b.c.Provider" id="defaultProvider" scope="prototype">
<constructor-arg ref="lifecycle" />
<constructor-arg ref="propertySetter" />
</bean>
<bean name="lifecycle" class="a.b.c.Lifecycle" scope="prototype">
<constructor-arg ref="someParam" />
... and more args
</bean>
<bean id="propertySetter" class="a.b.c.PropertySetter" scope="prototype">
<constructor-arg ref="lifecycle" />
</bean>
所以,我需要完全初始化提供商
生命周期
和 PropertySetter
里面,
和这个 PropertySetter
必须包含对同一生命周期
的引用,因为提供商
具有。
So, I need to have fully initialized Provider
with Lifecycle
and PropertySetter
inside,and this PropertySetter
must contain reference to same Lifecycle
, as the Provider
have.
当我将生命周期
和 propertySetter
定义为单身时,会导致很大的问题,因为
如果我创建了多个 Provider
,则 Provider
类的所有实例共享相同的生命周期
和属性setter ,它打破了应用程序逻辑。
When I define lifecycle
and propertySetter
as singletons, it causes big problems, becauseif I create more than one Provider
, all instances of Provider
class shares same lifecycleand property setter, and it's breaking application logic.
当我尝试将所有bean定义为原型时,生命周期在 Provider
中 PropertySetter
不再相同=>例外。
When I try to define all beans as prototypes, Lifecycles in Provider
and in PropertySetter
are not the same => exceptions again.
我有一个解决方案:转到提供商
仅生命周期
并在提供商 PropertySetter
/ code> java构造函数(通过扩展 Provider
)。
它运作良好,但仅限于我当地的环境。在生产代码中,我无法扩展3pty Provider
类,因此我无法使用此解决方案。
I have one solution: to pass to Provider
only Lifecycle
and create PropertySetter
inside Provider
java constructor (by extending Provider
).It is working well, but only in my local environment. In production code I can't extend 3pty Provider
class, so I can't use this solution.
请建议我,在这种情况下最合适的做法是什么?
Please advise me, what most appropriate to do in this situation?
推荐答案
你不需要扩展提供商
。只需创建自己的 ProviderFactory
,它将引用生命周期
并创建 PropertySetter
然后提供商
:
You don't need to extend Provider
. Just create your own ProviderFactory
that will take reference to lifecycle
and will create PropertySetter
and then Provider
:
public class ProviderFactory {
public static create(Lifecycle lc) {
return new Provider(lc, new PropertySetter(lc));
}
}
这是Spring声明:
Here is Spring declaration:
<bean id="defaultProvider" scope="prototype"
class="a.b.c.ProviderFactory" factory-method="create">
<constructor-arg ref="lifecycle" />
</bean>
这篇关于重复使用原型bean的相同实例两次 - Spring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!