Spring的threadlocal bean表现得像一个单身人士

时间:2014-10-20 17:33:41

标签: java spring

我们正在使用Spring 4.0.6.RELEASE,Java 8和Tomcat是我们的应用托管引擎。

我们有一个看起来像这样的春豆:

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

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

问题是当这个bean被注入不同的线程时,所有线程都获得相同的bean。每个线程都没有像我预期的那样得到它自己的bean。 bean注入@Autowired。是否还需要做其他事情才能获得线程本地bean?

我在xml中注册了这样的范围:

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

1 个答案:

答案 0 :(得分:3)

这里有一个问题,你必须另外提一下在你的bean之上创建什么样的代理 - 这个代理了解范围并管理底层的bean到相关的范围。这应该适合你:

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