'Spring Boot: Use ThreadLocal-variable or pass parameters
I´m wondering what is best practice with spring-boot and the already provided helper-classes that use ThreadLocal
for saving values suche as LocaleContextHolder
or RequestContextHolder
.
Actually I do not really like to pass parameters such as Request
or Locale
through every method call and blows up the signature until it is finally used. I would rather like to hide this information-details and obtain the required information where necessary within the service. But is the RequestContextHolder
or LocaleContextHolder
the right thing to use then or is it bad habbit to rely on ThreadLocal
operations? What is a recommended approach?
What problems might occur when relying on ThreadLocal
? I read about cleaning-up is an important thing, but as this is done already by spring-boot I would assume these are safe operations.
Thanks for your input
Solution 1:[1]
If you want to access request-dependent objects like Locale
or Request
and do not want to blow up your method's signature with additional paramters you can access them using static methods provided by RequestContextHolder
or LocaleContextHolder
.
Example:
public String getLocaleOfRequest(){
return LocaleContextHolder.getLocale()
}
There is actually no need to define ThreadLocal
s in your code for it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | glaures |