java - 跨多线程的 Spring bean 引用

标签 java multithreading spring dependency-injection

我遇到过如下场景:

MyBean - 在 XML 配置中定义。

我需要将 MyBean 注入(inject)到多个线程中。 但是我的要求是: 1)两个不同线程中检索到的引用应该不同 2) 但是无论我从单线程中检索 bean 多少次,我都应该得到相同的引用。

例如:

Thread1 {

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

Thread2 {

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

所以基本上 obj1 == obj2 但是 obj1 != obj3

最佳答案

您可以使用名为 SimpleThreadScope 的自定义作用域。

来自 Spring 文档:

As of Spring 3.0, a thread scope is available, but is not registered by default. For more information, see the documentation for SimpleThreadScope. For instructions on how to register this or any other custom scope, see Section 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>

关于java - 跨多线程的 Spring bean 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14689279/

相关文章:

如何使用java.net.URLConnection接收及发送HTTP请求

android - 如何在 Android 的后台线程上运行代码?

java - MongoDb 与 SpringData - 在后台创建所有索引的全局设置

java - 在自定义 JSR-303 validator 中使用 @Autowired 组件

java - TFS 结帐类似于 SVN 结帐

java - RAD 中的 NoClassDefFoundError

java - 如何修复 CWE-470 : Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection' )

c++ - 如何从不同线程调用 CMFCRibbonProgressBar 方法?

java - 并行流和 CompletableFuture 的区别

java - 如何解决循环依赖?