多线程 – 为什么spring不提供线程范围实现?

为什么Spring不提供线程范围实现?
有没有人在Web应用程序上下文中使用Spring的线程范围bean?
应该有一个标准的,清晰的描述如何做到这一点!
(SpringByExample有一个解决方案 – 我没有测试它 – 但它还不是主流.)

最佳答案
Spring确实提供了一个线程范围,但认情况下它没有注册.

现有的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 Spring ApplicationContext.

session

  • Scopes a single bean deFinition to the lifecycle of an HTTP Session.
    Only valid in the context of a web-aware Spring ApplicationContext.
    global

application

  • 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 Spring ApplicationContext.

然后文档做了说明

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并将其存储在其中一个池的重用线程中.根据您的使用情况,可能是不正确的行为.

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...