重复使用原型bean的相同实例两次 - Spring [英] Reuse same instance of prototype bean twice - Spring

查看:253
本文介绍了重复使用原型bean的相同实例两次 - Spring的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到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, because if I create more than one Provider, all instances of Provider class shares same lifecycle and 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆