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
Springdocumentation :Here an example of how to register the SimpleThreadScope scope :
Then, you’ll be able to use it in your bean’s definition :
You can also do the Scope registration declaratively :