如何在 Spring WebFlux 中获取语言环境?

Gea*_*any 4 java locale spring-boot spring-webflux

我想获取当前语言环境,但上下文始终返回默认语言环境。它适用于 MVC,但不适用于 WebFlux。

感谢您的帮助!

package co.example.demo.controller;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Locale;

@RestController
@RequestMapping("/hello")
public class HelloController {
    private final MessageSource messageSource;

    public HelloController(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @GetMapping
    public String hello() {
        Locale locale = LocaleContextHolder.getLocale();
        return messageSource.getMessage("hello", null, locale);
    }
}
Run Code Online (Sandbox Code Playgroud)

cac*_*co3 5

不要LocaleContextHolder在 WebFlux 环境中使用,而是添加Locale为方法参数:

@RestController
public class LocaleController {
    @GetMapping("/locale")
    String getLocale(Locale locale) {
        return locale.toLanguageTag();
    }
}
Run Code Online (Sandbox Code Playgroud)

测试:

$ curl localhost:8080/locale -H 'Accept-Language: en-US'
en-US
$ curl localhost:8080/locale -H 'Accept-Language: en-GB'
en-GB
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅:

  • 在内部,它依赖于“ThreadLocal”,由于其事件驱动的性质,不应该在 WebFlux 中使用它 (3认同)