【问题标题】:Spring bean references across multiple thread跨多个线程的 Spring bean 引用
【发布时间】:2013-01-19 07:15:31
【问题描述】:

我遇到过如下场景:

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

【问题讨论】:

    标签: java multithreading spring dependency-injection


    【解决方案1】:

    您可以使用名为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">
    

    您也可以以声明方式进行 Scope 注册:

    <?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 的请求都会返回 同一个线程的同一个实例。

      【讨论】:

        猜你喜欢
        • 2014-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多