Zipper
Zipper

Reputation: 7204

Spring's threadlocal bean is behaving like a singleton

We're using Spring 4.0.6.RELEASE, Java 8, and Tomcat is our app hosting engine.

We have a spring bean that looks like this:

@Service
@Scope("thread")
public class Foo {
   private Bar bar;

   public void setBar(Bar bar){
      this.bar = bar;
   }
}

The problem is that when this bean gets injected to different threads, all threads get the same bean. Each thread doesn't get it's own bean as I would have expected. The bean is injected with @Autowired. Is there something else that has to be done to get a thread local bean?

I registered the scope in the xml like this:

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

Upvotes: 2

Views: 872

Answers (1)

Biju Kunjummen
Biju Kunjummen

Reputation: 49935

There is a catch here, you have to additionally mention what kind of proxy to create on top of your bean - this proxy understands the scope and manages the bean underlying it to the relevant scope. This should work for you:

@Service
@Scope(value="thread", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Foo {

Upvotes: 3

Related Questions