I just start a new project based on Spring boot 2 + Webflux. On upgrading version of spring boot and replace spring-boot-starter-web
with spring-boot-starter-
With spring-boot-starter-webflux, there are
For example, to use a query parameter "lang" to explicitly control the locale:
Implement LocaleContextResolver
, so that
resolveLocaleContext()
returns a SimpleLocaleContext
determined by a GET parameter of "lang". I name this implementation QueryParamLocaleContextResolver
. Note that the default LocaleContextResolver
is an org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver
.
Create a @Configuration
class that extends DelegatingWebFluxConfiguration
. Override DelegatingWebFluxConfiguration.localeContextResolver()
to return QueryParamLocaleContextResolver
that we just created in step 1. Name this configuration class WebConfig
.
In WebConfig
, override DelegatingWebFluxConfiguration.configureViewResolvers()
and add the ThymeleafReactiveViewResolver
bean as a view resolver. We do this because, for some reason, DelegatingWebFluxConfiguration
will miss ThymeleafReactiveViewResolver
after step 2.
Also, I have to mention that, to use i18n with the reactive stack, this bean is necessary:
@Bean
public MessageSource messageSource() {
final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:/messages");
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setDefaultEncoding("UTF-8");
messageSource.setCacheSeconds(5);
return messageSource;
}
After creating a natural template, some properties files, and a controller, you will see that:
localhost:8080/test?lang=zh
gives you the Chinese version
localhost:8080/test?lang=en
gives you the English version
Just don't forget in
, otherwise you may see some nasty display of Chinese characters.