【问题标题】:Nested property in ResourceBundleMessageSourceResourceBundleMessageSource 中的嵌套属性
【发布时间】:2016-04-09 16:50:04
【问题描述】:

如果 Spring 可以自动解析嵌套属性,我需要帮助。我使用的是 Spring 4.2.4,Java 8,属性文件看起来像 -

# messages.properties
company.name=XYZ
welcome.message=Dear Customers of ${company.name}
about.company=${company.name} is blah blah

我们有一个自定义的本地化实现来从 i18 的资源包中获取字符串,如下定义-

public String get(Locale locale, String key, Object... arguments) {
String pattern = this.getString(locale, key);
MessageFormat formatter = new MessageFormat(pattern, locale);
StringBuffer buffer = new StringBuffer();
formatter.format(arguments, buffer, null);
return buffer.toString();
}

我希望能够使用 get(locale, "welcome.message") 之类的方法,并希望将其呈现为 XYZ 的亲爱的客户。

目前它在 MessageFormat 中无法正常工作。有没有办法让spring自动解决这个问题。

【问题讨论】:

    标签: java spring-mvc internationalization


    【解决方案1】:

    我在我的控制器中使用 MessageSource 这样做

    @Inject
    private MessageSource message;
    
    protected String getMessage(String key, Object[] arguments) {
        return message.getMessage(key, arguments, LocaleContextHolder.getLocale());
    }
    

    【讨论】:

    • 感谢您的回复。因此,对于上述属性文件设置,您将如何解决“XYZ 的亲爱的客户”。消息。
    • 你调用 String name =getMessage("company.name", null);然后 String message = getMessage("welcome.message", name)
    • 我像{0}的尊敬的客户一样使用或尝试将公司作为参数发送
    • 索引有效,但我正在寻找想法,如果有一种方法可以通过基于名称的嵌套而不是基于索引来自动解决这个问题。
    【解决方案2】:

    您现在可以使用花括号(不带符号 $)。 它适用于 Spring 5(针对 5.3.6 和 5.3.7 测试):

    # messages.properties
    company.name=XYZ
    welcome.message=Dear Customers of {company.name}
    about.company={company.name} is blah blah
    

    【讨论】:

      猜你喜欢
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 2011-02-25
      • 2017-11-29
      相关资源
      最近更新 更多