Since version 3.0, Spring has a basic notion of thread scope : the SimpleThreadScope
. It looks like it can feet what you ask, but it has some limitations :
- it is not registered by default with containers but must explicitely be
- it performs no cleanup on its beans.
If you can accomodate with those limitations, you can register the scope programatically :
Scope threadScope = new SimpleThreadScope();
appContext.getBeanFactory().registerScope("thread", threadScope);
or in xml config :
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="thread">
<bean class="org.springframework.context.support.SimpleThreadScope"/>
</entry>
</map>
</property>
</bean>
This works the same in Spring 3 and Spring 4. If you want to inject a thread scoped bean in a singleton bean, you have to declare an aop scoped-proxy on it :
<bean id="bar" class="x.y.Bar" scope="thread">
<property name="name" value="Rick"/>
<aop:scoped-proxy/>
</bean>
<bean id="foo" class="x.y.Foo">
<property name="bar" ref="bar"/>
</bean>
(All examples from Spring Framework Reference Documentation).
If you have to do some cleanup, you can look at this document Spring by Example Custom Thread Scope Module that shows an enhanced version of SimpleThreadScope
.
But I am not sure you really want that, unless all threads continuously use the thread scoped beans, or memory is not really a concern. Because in that design pattern, if only one session at a time needs the bean, but it is served by several threads (assuming other requests do not need the bean), all the threads will get a different instance of the bean, whereas with a pool only one instance would have been used.
You will find an example of using a CommonsPoolTargetSource
with Apache Common Pools in this other post from SO How to pool objects in Spring?. Extract from the post :
<bean id="simpleBeanTarget" class="com.bean.SimpleBean" scope="prototype"/>
<bean id="poolTargetSource" class="org.springframework.aop.target.CommonsPoolTargetSource">
<property name="targetBeanName" value="simpleBeanTarget" />
<property name="maxSize" value="2" />
</bean>
<bean id="simpleBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="targetSource" ref="poolTargetSource" />
</bean>
The example use a ProxyFactoryBean
to give an aop proxy to allow injection of simpleBean
in a singleton bean, provided it is injected as an interface.