为什么Spring不提供线程范围实现?
有没有人在Web应用程序上下文中使用Spring的线程范围bean?
应该有一个标准的,清晰的描述如何做到这一点!
(SpringByExample有一个解决方案 – 我没有测试它 – 但它还不是主流.)
最佳答案
Spring确实提供了一个线程范围,但默认情况下它没有注册.
原文链接:https://www.f2er.com/spring/431972.html现有的bean作用域在文档here中定义.
singleton
- (Default) Scopes a single bean definition to a single object instance per Spring IoC container.
prototype
- Scopes a single bean definition to any number of object
instances.request
- Scopes a single bean definition to the lifecycle of
a single HTTP request; that is,each HTTP request has its own instance
of a bean created off the back of a single bean definition. Only valid
in the context of a web-aware SpringApplicationContext
.session
- Scopes a single bean definition to the lifecycle of an HTTP Session.
Only valid in the context of a web-aware Spring ApplicationContext.
globalapplication
- Scopes a single bean definition to the lifecycle of a
ServletContext
. Only valid in the context of a web-aware Spring
ApplicationContext
.websocket
- Scopes a single bean definition to the lifecycle of a
WebSocket
. Only
valid in the context of a web-aware SpringApplicationContext
.
然后文档做了说明
As of Spring 3.0,a thread scope is available,but is not registered
by default. For more information,see the documentation for
07001.
请注意,与原型范围类似,线程范围
[
SimpleThreadScope
] does not clean up any objects associated with it.
此线程范围实现使用ThreadLocal来存储bean.
您无法检测到在Java中结束/死亡的线程,因此Spring IOC容器无法明确知道何时从ThreadLocal中删除Bean并调用生命周期方法的任何结尾.那么责任落在开发者身上.
在使用此范围时要小心.例如,在线程池上下文中,可能已经创建了一个bean并将其存储在其中一个池的重用线程中.根据您的使用情况,可能是不正确的行为.