Why doesn't Spring provide a thread scope implementation?
Has anyone used thread scoped beans with Spring in a web application context?
There should be a standard, clear description of how to do this!
(SpringByExample has a solution—I didn't test it—but it is not mainstream yet.)
Spring – Why doesn’t spring provide a thread scope implementation
multithreadingscopespring
Best Answer
Spring does provide a thread scope, but it is not registered by default.
The existing bean scopes are defined in the documentation, here.
The documentation then makes a note
Note that, similarly to the prototype scope, the thread scope
This thread scope implementation uses a
ThreadLocal
to store beans. You cannot detect aThread
ending/dying in Java, so the Spring IOC container cannot explicitly know when to remove the beans from theThreadLocal
and invoke any end of lifecycle methods. That responsibility then falls on the developer.Be careful where you use this scope. For example, in a thread pooling context, a bean might already have been created and stored in one of the pools' reused threads. Depending on your use case, that might be the incorrect behavior.