How to configure i18n in Spring boot 2 + Webflux + Thymeleaf?

后端 未结 3 1816
清酒与你
清酒与你 2021-02-19 11:10

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-

3条回答
  •  日久生厌
    2021-02-19 11:27

    Another solution with spring boot starter web flux, which is much more cleaner, is to define your own HttpHandler using WebHttpHandlerBuilder in which you can set your LocaleContextResolver.

    Documentation (see 1.2.2. WebHandler API) : https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-config-customize

    MyLocaleContextResolver.java

    public class MyLocaleContextResolver implements LocaleContextResolver {
    
    
        @Override
        public LocaleContext resolveLocaleContext(ServerWebExchange exchange) {      
            return new SimpleLocaleContext(Locale.FRENCH);        
        }
    
        @Override
        public void setLocaleContext(ServerWebExchange exchange, LocaleContext localeContext) {
            throw new UnsupportedOperationException();
        }
    }
    

    Then in a config file (annotated with @Configuration) or in your spring boot application file, defined your own HttpHandler bean.

    Application.java

    @SpringBootApplication
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
        @Bean
        public HttpHandler httpHandler(ApplicationContext context) {
    
            MyLocaleContextResolver localeContextResolver = new MyLocaleContextResolver();
    
            return WebHttpHandlerBuilder.applicationContext(context)
                    .localeContextResolver(localeContextResolver) // set your own locale resolver
                    .build();
    
        }
    
    }
    

    That's it!

提交回复
热议问题