【问题标题】:Spring MessageSource seems to ignore property fallbackToSystemLocaleSpring MessageSource 似乎忽略了属性 fallbackToSystemLocale
【发布时间】:2015-05-28 19:08:42
【问题描述】:

我在配置 Spring MessageSource 以忽略我的系统语言环境时遇到问题。当我使用 null 语言环境参数调用 getMessage 时,我希望我的 MessageSource 选择默认属性文件 messages.properties。相反,它选择了messages_en.properties。当我将此属性文件的名称更改为 messages_fr.properties 时,会选择默认属性文件。我的系统语言环境是“en”。所以看起来 MessageSource 忽略了我设置为 false 的 fallbackToSystemLocale 属性。

此行为与 Spring 版本 4.1.4 和 4.1.5 相同。

消息源配置:

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="fallbackToSystemLocale" value="false"></property>
    <property name="basenames">
        <list>
            <value>locale/messages</value>
        </list>
    </property>
    <property name="defaultEncoding" value="UTF-8"></property>
</bean>

获取消息:

String message = messageSource.getMessage("user.email.notFound", new Object[] {email}, null);

感谢您的建议!

【问题讨论】:

    标签: java spring spring-java-config


    【解决方案1】:

    fallbackToSystemLocale 旨在引导消息源在您使用 locale=null 调用它们时执行的操作

    fallbackToSystemLocale 控制当您请求所请求的本地不存在的消息(代码)时要执行的操作 - 因为根本没有该语言的消息属性文件,或者只是因为消息文件不包含消息代码

    另一方面,当您使用locale=null (messageSource.getMessage("key", null);) 调用getMessage 时,区域设置将由Locale.getDefault 设置

    org.springframework.context.support.AbstractMessageSource:

    protected String getMessageInternal(String code, Object[] args, Locale locale) {
        ...
        if (locale == null) {
            locale = Locale.getDefault();
        }
        ...
    

    在考虑fallbackToSystemLocale 属性之前。

    Therfore 最简单的 hack-arround(它不是一个workarround,它是一个hack),将使用您不支持的语言而不是nullmessageSource.getMessage("key", new Locale("XX"));

    【讨论】:

    • 感谢您的好回答。无论如何,您不觉得这种行为不合逻辑吗?如果提供了空语言环境,我希望使用默认消息属性文件。如果我想使用本地系统,我会做类似 messageSource.getMessage("key", locale==null ? Locale.getDefault() : locale); 的事情。即 Wicket 框架在我写作时解决了这个问题,对我来说似乎更好。我可能会扩展 ResourceBundleMessageSource 类并覆盖 getMessageInternal 以反映我的需求。如果它当然没有被宣布为最终的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    相关资源
    最近更新 更多