如何使用Pooled Spring bean而不是Singleton?

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

我在这里 (spring文档)找到了一种方法来实现这一点,方法是将EJB以EJB样式汇集在一起​​,方法如下:

  • 将目标bean声明为范围“prototype”。
  • 声明一个池提供程序,它将提供有限数量的池化“目标”实例。
  • 声明一个“ProxyFactoryBean”,这个function对我来说并不清楚。

这是这个bean的声明:

 ... properties omitted          

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

    

什么应该是“ref”的价值?

您不能使用属性来获取原型的实例。
一种选择是使用查找方法(参见章节3.3.7.1 )
在代码中获取bean的另一个选择:使com.mycompany.ClientOfTheBusinessObject实现ApplicationContextAware接口,然后调用context.getBean("clientBean")

我很确定你可以用一种不太复杂的方式限制同步线程的数量。 您是否看过Java Concurrency API,特别是在Executors.newFixedThreadPool()?

我使用java-configuration在接口上构建代理,使用apache commons-pool处理池,以实现调用级别池。

请注意spring示例中第三个bean的名称: – “businessObject”

这意味着你应该访问公共池的bean。

对于您的情况,如果您需要自己的客户端bean,您可以按如下方式使用它。 但在这种情况下,不需要businessObject.:-

  ... properties omitted         Java classes:- public class ClientOfTheBusinessObject{ CommonsPoolTargetSource 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); } }