如何使用池化Spring Bean代替Singleton的bean?

问题描述 投票:2回答:5

出于效率原因,我有兴趣限制同时使用Spring应用程序上下文的bean的线程数(我不希望在我的[[limited内存中处理的线程数为[[unlimited]个)] 。

我发现here(春季文档)通过以下方式通过以EJB样式合并bean来实现此目的的方法:

将目标bean声明为范围“原型”。

    声明将提供有限数量的池“目标”实例的池提供程序。
  • 声明一个对我不清楚的功能“ ProxyFactoryBean”。
  • 这里是此bean的声明:
  • <bean id="businessObjectTarget" class="com.mycompany.MyBusinessObject" scope="prototype"> ... properties omitted </bean> <bean id="poolTargetSource" class="org.springframework.aop.target.CommonsPoolTargetSource"> <property name="targetBeanName" value="businessObjectTarget"/> <property name="maxSize" value="25"/> </bean> <bean id="businessObject" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="targetSource" ref="poolTargetSource"/> <property name="interceptorNames" value="myInterceptor"/> </bean>

    我的问题是,当我将声明另一个bean以使用“ businessObjectTarget”的池化实例时,应该怎么做?我的意思是,当我尝试做这样的事情时:

    <bean id="clientBean" class="com.mycompany.ClientOfTheBusinessObject">
      <property name="businessObject" ref="WHAT TO PUT HERE???"/>
    </bean>
    

    “ ref”的值应该是什么?

  • java multithreading spring ejb
    5个回答
    5
    投票

    0
    投票

    0
    投票

    0
    投票
    这意味着这是您应该从中访问公用池的bean。

    对于您的情况,如果您需要自己的客户Bean,则可以按以下方式进行操作。但是在这种情况下,不需要businessObject。

    <bean id="businessObjectTarget" class="com.mycompany.MyBusinessObject" scope="prototype"> ... properties omitted </bean> <bean id="poolTargetSource" class="org.springframework.aop.target.CommonsPoolTargetSource"> <property name="targetBeanName" value="businessObjectTarget"/> <property name="maxSize" value="25"/> </bean> <bean id="clientBean" class="com.mycompany.ClientOfTheBusinessObject"> <property name="poolTargetSource" ref="poolTargetSource"/> </bean> Java classes:- public class ClientOfTheBusinessObject{ CommonsPoolTargetSource poolTargetSource; //<getter and setter for poolTargeTSource> public void methodToAccessCommonPool(){ //The following line gets the object from the pool.If there is nothing left in the pool then the thread will be blocked.(The blocking can be replaced with an exception by changing the properties of the CommonsPoolTargetSource bean) MyBusinessObject mbo = (MyBusinessObject)poolTargetSource.getTarget(); //Do whatever you want to do with mbo //the following line puts the object back to the pool poolTargetSource.releaseTarget(mbo); } }


    0
    投票
    © www.soinside.com 2019 - 2024. All rights reserved.