Spring by Example Custom Thread Scope Module

David Winterfeldt

2008


The Custom Thread Scope module is a custom scope implementation for providing thread scoped beans. Every request for a bean will return the same instance for the same thread. A Runnable must be wrapped in a ThreadScopeRunnable if destruction callbacks should occur on a thread scoped bean.

[Note]Note

See SimpleThreadScope in Spring 3.0 for a Spring Framework implementation. Athough it doesn't support destruction callbacks (this implementation does when using a custom Callable or Runnable).

1. Spring Configuration

The threadCounter bean is set to use the custom ThreadScope and the CustomScopeConfigurer registers the custom scope.

                
<bean id="threadCounter" 
      class="org.springbyexample.bean.scope.thread.Counter" 
      scope="thread" />

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="thread">
                <bean class="org.springbyexample.bean.scope.thread.ThreadScope"/>
            </entry>
        </map>
    </property>
</bean>