Spring bean引用跨多个线程

use*_*968 7 java spring multithreading dependency-injection

我遇到过如下情况:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Jea*_*ond 10

您可以使用名为的自定义范围SimpleThreadScope.

Spring文档:

截止到Spring 3.0,线程范围可用,但默认情况下未注册.有关更多信息,请参阅SimpleThreadScope的文档 .有关如何注册此范围或任何其他自定义范围的说明,请参见第3.5.5.2"使用自定义范围".

这里是一个如何注册SimpleThreadScope范围的示例:

Scope threadScope = new SimpleThreadScope();
beanFactory.registerScope("thread", threadScope);
Run Code Online (Sandbox Code Playgroud)

然后,您将能够在bean的定义中使用它:

<bean id="foo" class="foo.Bar" scope="thread">
Run Code Online (Sandbox Code Playgroud)

您还可以声明性地进行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>
Run Code Online (Sandbox Code Playgroud)