I have a service which has methods sending emails asyncronously. Sender method has an @Async
annotation. But when I try to use current locale in that method, It always the default one. So question is how to pass locale to @Async
methods.
3 Answers
The solution of chunhoong worked for me, but It's not so semantic. There was a better solution for me: Set the same request context for all threads. The main and all the @Async threads should share the DispatcherServlet context (setThreadContextInheritable(true)). It worked like a charm:
@SpringBootApplication
public class CoreApplication {
public static void main(String[] args) {
SpringApplication
.run(CoreApplication.class, args)
.getBean(DispatcherServlet.class)
.setThreadContextInheritable(true);
}
}
PS: This helped me a lot: https://github.com/spring-projects/spring-boot/issues/14079
I believe you are accessing your current locale using LocaleContextHolder.
Before execute your async method, set your current locale into LocaleContextHolder with inheritable flag set to true, eg:
Locale currentLocale = LocaleContextHolder.getLocale();
LocaleContextHolder.setLocale(currentLocale, true);
The LocaleContext will be inherited by any child threads spawned by the current thread when the inheritable flag is set to true, which behaves like a thread-local.
It is possible to implement custom AsyncTaskExecutor
which would take a Locale as a parameter. Then it would set a locale to its context.
public interface LocaleAsyncTaskExecutor extends AsyncTaskExecutor {
void execute(Runnable task, Locale locale);
}
LocaleContextHolder
isn't an option as that is based on aThreadLocal
(that is also why you are getting the defaultLocale
instead of the one you expect).