Is it OK to use ThreadLocal for storing the requested Locale?

北城余情 提交于 2019-12-05 02:26:16

This approach is perfectly valid. For example, Spring makes Locale available using ThreadLocal through RequestContextListener and LocaleContextHolder.

If you create a custom implementation, make sure you handle your ThreadLocal (set/remove) properly.

Although, common practise I don't like to do localizing "deep" within the application.

Intead of this:

public String getSomeText() {
  return getSomeText(myThreadLocalLocale.get());
}

We do this:

public LocalizableText getSomeText() {
  return new LocalizableText(resourceBundle, "someText");
}

And then do, e.g. in a JSP or output layer:

<%= localizable.getString(locale) %>

The logic itself is language agnostic. We have cases where, after some processing, the application sends out the result by mail, logs it and presents it to the web user in all different languages. So processing together with result generation and then localization must be separate.

Using a thread local like you describe is a very common pattern in web applications. See this class in the Spring API as an example:

org.springframework.web.context.request.RequestContextHolder

Use a servlet filter (or similar) to both set the locale in a thread local, and then CLEAR the locale value after the server finished each request. Instead of injecting it in each place it is used, use a static factory/accessor method similar to RequestContextHolder: RequestContextHolder.getRequestAttributes().

ThreadLocal is bad practice. It's global variables and there are plenty of articles about how bad that is, in any language. The fact that Spring uses it does not justify using it. I like the solution cruftex has given. Avoid passing data via global variables.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!