Spring bean multiple thread links

I came across a script as shown below:

MyBean - Defined in the XML configuration.

I need to inject MyBean into multiple threads. But my requirements: 1) The link received in two different threads should be different 2) But I have to get the same link, no matter how many times I extract the bean from one thread.

For example:

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

In principle, obj1 == obj2 , but obj1 != obj3

+7
source share
2 answers

You can use a custom scope called SimpleThreadScope .

From the Spring documentation:

As with Spring 3.0 , the stream area is accessible but not registered by default. See the documentation for SimpleThreadScope for more information. For instructions on registering this or any other custom volume, see section 3.5.5.2, β€œUsing Custom Volume” .

Here is an example of how to register a SimpleThreadScope region:

 Scope threadScope = new SimpleThreadScope(); beanFactory.registerScope("thread", threadScope); 

Then you can use it in the definition of bean:

 <bean id="foo" class="foo.Bar" scope="thread"> 

You can also declare the registration area:

 <?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> 
+10
source

What you need is a new local custom thread area . You can either implement your own or use it here .

The Custom Scope module is a special implementation of a scope for providing a scope with beans. Each request for a bean will return the same instance for the same thread.

+2
source

All Articles