[英]Is LocaleContextHolder safe in service layer
According to official doc, LocaleContextHolder is: 根据官方文档,LocaleContextHolder是:
Simple holder class that associates a LocaleContext instance with the current thread.
简单的holder类,它将LocaleContext实例与当前线程相关联。
So it is tied to current thread
, but is this talking about the Thread
thread or a thread of current request. 所以它与当前
thread
,但这是关于Thread
线程还是当前请求的线程。
Apologize if it is a dumb question, I am not a LocaleContextHolder is not tied to a HTTP session or something so that it is safe to use in any service layer class. 如果它是一个愚蠢的问题,请道歉,我不是一个LocaleContextHolder没有绑定到HTTP会话或其他东西,以便在任何服务层类中使用是安全的。
If you look at the source code for LocaleContextHolder
, you will notice it has a ThreadLocal
variable (it has two actually) 如果查看
LocaleContextHolder
的源代码,你会发现它有一个ThreadLocal
变量(实际上有两个)
private static final ThreadLocal<LocaleContext> localeContextHolder =
new NamedThreadLocal<LocaleContext>("Locale context");
You can read about what a ThreadLocal
is but for our sake, consider it a data structure that maps the ID of the current executing thread to an object of its generic type, LocaleContext
here. 您可以阅读
ThreadLocal
内容但是为了我们的目的,请将其视为将当前正在执行的线程的ID映射到其泛型类型的对象LocaleContext
的数据结构。
A Servlet container has a pool of threads it uses to handle client requests. Servlet容器有一个用于处理客户端请求的线程池。 When a request comes in, it will extract one of these threads and execute your servlet's
service()
method. 当请求进入时,它将提取其中一个线程并执行您的servlet的
service()
方法。 With Spring, this results in DispatcherServlet
executing and your @Controller
's handler method being called. 使用Spring,这会导致
DispatcherServlet
执行并调用@Controller
的处理程序方法。 This all happens in that original Thread
the servlet container chose. 这一切都发生在servlet容器选择的原始
Thread
中。
So when your @Service
class' method gets called, you're still in that same thread. 所以当你的
@Service
类'方法被调用时,你仍然在同一个线程中。
The ThreadLocal
in LocaleContextHolder
is set()
at some point early on in request processing, in FrameworkServlet
(which is the parent type of DispatcherServlet
) method initContextHolders()
called by processRequest()
in each of doGet()
, doPost()
, etc. methods. 所述
ThreadLocal
在LocaleContextHolder
是set()
在某个点早在请求处理,在FrameworkServlet
(其为母体的类型DispatcherServlet
)方法initContextHolders()
通过被称为processRequest()
中的每个的doGet()
doPost()
等等。方法。 The Locale
is built from the HttpServletRequest
with its getLocale()
method. Locale
是使用其getLocale()
方法从HttpServletRequest
构建的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.