【问题标题】:Spring MessageSource find by several localesSpring MessageSource 由几个语言环境查找
【发布时间】:2018-02-15 09:03:07
【问题描述】:

我有以下情况:我从移动设备获取语言环境列表,我需要检查我的 MessageSource 是否与传递的列表匹配。因此,默认情况下,我可以通过一个语言环境进行检查,如果 spring 找不到匹配项,它将使用默认语言环境,但在我的情况下,我需要检查语言环境列表。春季是否支持此功能?

【问题讨论】:

  • I need to check my MessageSource whether it has any matches. 如果您正在寻找服务器支持的所有语言环境,那么您可以使用Locale.getAvailableLocales()
  • 我需要获取 spring 解决的所有可用语言环境。
  • 我认为没有任何 API 或方法可以从中获取所有已解析的 spring 语言环境。我认为我们可以在 MessageSource 中按优先级顺序尝试所有带有消息的语言环境。如果消息未翻译,则返回默认消息。在内部为每条消息和语言环境维护一个哈希图,因此它也不会影响性能。
  • 你能提供一些例子吗?不确定我是否理解您的建议
  • 或者您的意思可能是尝试获取 n 次以从 MessageSource 获取消息?

标签: java spring internationalization


【解决方案1】:

我能够通过以下方式修复它:

    @Bean
    public CustomMessageSource messageSource() {
        CustomReloadableResourceBundleMessageSource messageSource = new CustomReloadableResourceBundleMessageSource();
        messageSource.setFallbackToSystemLocale(false);
        messageSource.setBasename("messages");
        return messageSource;
    }


    public class CustomReloadableResourceBundleMessageSource extends
    ResourceBundleMessageSource implements CustomMessageSource {
    public String getMessage(String code, List<Locale> locales) {
        return locales.stream().map(locale -> getMessage(code, null, locale))
            .filter(StringUtils::isNotEmpty).findFirst()
            .orElse(getMessage(code, null, Locale.ENGLISH));
    }
}

fallbackToSystemLocale 属性设置为 false 非常重要,因为否则系统会为每个未解析的消息使用默认语言环境。

【讨论】:

  • 这不是一个好的答案,如果找不到第一个语言环境,则会返回 NoSuchMessageException。调用 getMessage(code, null, locale) 时应该捕获异常并返回 null
猜你喜欢
  • 2023-03-31
  • 2011-09-14
  • 2011-09-20
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多