我遇到过如下场景:
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/