2015-03-25 191 views
4

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

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

MessageSource的配置:

<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); 

感谢您的咨询!

回答

3

fallbackToSystemLocale旨在引导什么消息源并当你调用他们locale=null

fallbackToSystemLocale控制,当你请求的消息(代码)做什么,不为所要求的本地存在 - 无论是因为没有消息属性的语言文件,同时,或只是因为消息文件不包含消息代码

在当你调用getMessagelocale=nullmessageSource.getMessage("key", null);),那么区域将被设置另一方面

org.springframework.context.support.AbstractMessageSource:

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

fallbackToSystemLocale财产采取帐户。

Therfore的easyest 破解 -arround(这是不是一个workarround这是一个黑客),将使用您不支持,而不是null语言: messageSource.getMessage("key", new Locale("XX"));

+0

感谢一个很好的答案。无论如何,你不觉得这种行为不合逻辑吗?我期望在提供空区域设置的情况下使用默认的消息属性文件。如果我想使用系统本地,我会做'messageSource.getMessage(“key”,locale == null?Locale.getDefault():locale);''。即Wicket框架在我编写时解决了这个问题,这对我来说似乎更好。 我可能会扩展'ResourceBundleMessageSource'类并覆盖'getMessageInternal'来反映我的需求。如果它没有被宣布为当然是最终的:) – 2015-03-25 12:57:30