微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐