【问题标题】:How to get locale in Spring WebFlux?如何在 Spring WebFlux 中获取语言环境?
【发布时间】:2020-10-11 09:36:21
【问题描述】:

我想获取当前语言环境,但上下文总是返回默认语言环境。它适用于 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);
    }
}

【问题讨论】:

  • 您期望的语言环境是什么以及它返回的内容是什么?
  • @DhawalKapil 我有 message.propertiesmessages_fr.properties 但 webflux 总是返回默认语言环境 en 而不是 fr。用mvc没问题。
  • 我认为这取决于当前的 JVM 语言环境。我不确定是否有任何与之相关的 Webflux/Web。

标签: java spring-boot locale spring-webflux


【解决方案1】:

之前我在我的项目中使用 spring-web 依赖项,并且能够从 WebRequest 获取语言环境。

但是当我们将项目从 spring-web 迁移到 spring-web-flux 时,我们可以使用 LocaleContextHolder 获取语言环境,如下所示:

Locale locale = LocaleContextHolder.getLocale();

【讨论】:

    【解决方案2】:

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

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

    测试:

    $ curl localhost:8080/locale -H 'Accept-Language: en-US'
    en-US
    $ curl localhost:8080/locale -H 'Accept-Language: en-GB'
    en-GB
    

    更多信息见:

    【讨论】:

    • 你能告诉我为什么LocaleContextHolder不能与WebFlux一起工作吗?
    • 在内部它依赖于ThreadLocal,由于其事件驱动的性质,它不应该在 WebFlux 中使用
    猜你喜欢
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多