Spring by Example Custom Thread Scope Module

David Winterfeldt


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.


See SimpleThreadScope, which was added in Spring 3.0, for a Spring Framework implementation Although the Spring version doesn't support destruction callbacks (this implementation does when using a custom Runnable).

1. Spring Configuration

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

<bean id="threadCounter" 
      scope="thread" />

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