Reuse same instance of prototype bean twice - Spring

徘徊边缘 提交于 2019-12-06 09:33:14

问题


I have a problem with Spring: I need to reuse the same instance of bean twice, but not making it singleton.

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>

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.

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.

When I try to define all beans as prototypes, Lifecycles in Provider and in PropertySetter are not the same => exceptions again.

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?


回答1:


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));
  }
}

Here is Spring declaration:

<bean id="defaultProvider" scope="prototype" 
      class="a.b.c.ProviderFactory" factory-method="create">
    <constructor-arg ref="lifecycle" />
</bean>


来源:https://stackoverflow.com/questions/12746740/reuse-same-instance-of-prototype-bean-twice-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!