I have come across a scenario as below:
MyBean - Defined in XML Configuration.
I need to inject MyBean into multiple threads. 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.
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
You can use the custom scope named SimpleThreadScope
.
From the Spring
documentation :
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”.
Here an example of how to register the SimpleThreadScope scope :
Scope threadScope = new SimpleThreadScope();
beanFactory.registerScope("thread", threadScope);
Then, you'll be able to use it in your bean's definition :
<bean id="foo" class="foo.Bar" scope="thread">
You can also do the Scope registration declaratively :
<?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. 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. Every request for a bean will return the same instance for the same thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With