[英]Spring bean references across multiple thread
I have come across a scenario as below: 我遇到过如下情况:
MyBean - Defined in XML Configuration. MyBean - 在XML配置中定义。
I need to inject MyBean into multiple threads. 我需要将MyBean注入多个线程。 But my requirements is: 1) The reference retrieved in two different threads should be different 2) But I should get the same reference irrespective how many times I retrieve bean from single thread.
但我的要求是:1)在两个不同的线程中检索的引用应该是不同的2)但是我应该获得相同的引用,而不管从单个线程检索bean的次数。
Eg : 例如:
Thread1 {
run() {
MyBean obj1 = ctx.getBean("MyBean");
......
......
MyBean obj2 = ctx.getBean("MyBean");
}
}
Thread2 {
run(){
MyBean obj3 = ctx.getBean("MyBean");
}
}
So Basically obj1 == obj2
but obj1 != obj3
所以基本上
obj1 == obj2
但是obj1 != obj3
You can use the custom scope named SimpleThreadScope
. 您可以使用名为
SimpleThreadScope
的自定义作用域。
From the Spring
documentation : 从
Spring
文档:
As of
Spring 3.0
, a thread scope is available, but is not registered by default.从
Spring 3.0
,线程范围可用,但默认情况下未注册。 For more information, see the documentation for SimpleThreadScope .有关更多信息,请参阅SimpleThreadScope的文档。 For instructions on how to register this or any other custom scope, see Section 3.5.5.2, “Using a custom scope” .
有关如何注册此范围或任何其他自定义范围的说明,请参见第3.5.5.2节“使用自定义范围” 。
Here an example of how to register the SimpleThreadScope scope : 这里是一个如何注册SimpleThreadScope范围的示例:
Scope threadScope = new SimpleThreadScope();
beanFactory.registerScope("thread", threadScope);
Then, you'll be able to use it in your bean's definition : 然后,您将能够在bean的定义中使用它:
<bean id="foo" class="foo.Bar" scope="thread">
You can also do the Scope registration declaratively : 您还可以声明性地进行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>
What you require is a new Thread Local custom scope . 您需要的是一个新的Thread Local自定义范围 。 You can either implement your own or use the one here .
你可以实现自己的,也可以在这里使用 。
The Custom Thread Scope module is a custom scope implementation for providing thread scoped beans.
自定义线程范围模块是一个自定义范围实现,用于提供线程范围的bean。 Every request for a bean will return the same instance for the same thread.
对bean的每个请求都将为同一个线程返回相同的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.