2013-02-04 37 views
7

我遇到以下場景:跨多個線程的Spring bean引用

MyBean - 在XML配置中定義。

我需要將MyBean注入多個線程。 但我的要求是: 1)在兩個不同的線程中檢索到的引用應該不同 2)但是我應該得到相同的引用,而不管我從單線程檢索bean多少次。

如:

Thread1 { 

    run() { 
     MyBean obj1 = ctx.getBean("MyBean"); 
     ...... 
     ...... 
     MyBean obj2 = ctx.getBean("MyBean"); 
    } 
} 

Thread2 { 

    run(){ 
     MyBean obj3 = ctx.getBean("MyBean"); 
    } 
} 

所以基本上obj1 == obj2obj1 != obj3

回答

10

您可以使用名爲SimpleThreadScope的自定義範圍。

Spring文檔:

由於Spring 3.0,線程範圍是可用的,但沒有登記默認 。有關更多信息,請參閱 SimpleThreadScope的文檔。有關如何註冊此或 任何其他自定義範圍的說明,請參見部分3.5.5.2, 「Using a custom scope」

這裏如何註冊SimpleThreadScope範圍的例子:

Scope threadScope = new SimpleThreadScope(); 
beanFactory.registerScope("thread", threadScope); 

然後,你就可以在你的bean的定義中使用它:

<bean id="foo" class="foo.Bar" scope="thread"> 

你也可以做範圍註冊聲明:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:aop="http://www.springframework.org/schema/aop" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
      http://www.springframework.org/schema/aop 
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> 

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

    <bean id="foo" class="foo.Bar" scope="thread"> 
     <property name="name" value="bar"/> 
    </bean> 

</beans> 
2

你所需要的是一個新的線程本地定製範圍。您可以實施自己的或use the one here

自定義線程作用域模塊是爲 提供線程作用域bean的自定義作用域實現。每個bean的請求將返回 同一個線程的同一個實例。