Search code examples
javamultithreadingspringejb

How to use Pooled Spring beans instead of Singleton ones?


For efficiency reasons, I am interested in limiting the number of threads that simultaneously uses the beans of the Spring application context (I don't want an unlimited number of threads proccessing in my limited memory).

I have found here (spring documentation) a way to achieve this by pooling the beans in a EJB style, by doing the following:

  • Declare the target bean as scope "prototype".
  • Declare a Pool provider that will deliver a limited number of pooled "target" instances.
  • Declare a "ProxyFactoryBean" which function is not clear to me.

Here is the declaration of this beans:

<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>

My problem is that when I will declare another bean to use pooled instances of the "businessObjectTarget", how should I do it? I mean, when i try to do something like this:

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

What should be the value of the "ref" ??


Solution

  • You cannot use properties to get instances of prototypes.
    One option is to use the lookup methods (see chapter 3.3.7.1)
    Another option to get your bean in code: make your com.mycompany.ClientOfTheBusinessObject to implement the ApplicationContextAware interface and then call context.getBean("clientBean")