我在配置Spring MessageSource以忽略我的系统区域设置时遇到问题。当我使用null locale参数调用getMessage时,我希望我的MessageSource选择默认属性文件messages.properties。相反,它选择messages_en.properties。当我将此属性文件的名称更改为messages_fr.properties时,将选择默认属性文件。我的系统区域设置是'en'。所以似乎MessageSource忽略了我设置为false的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);
感谢您的任何建议!
答案 0 :(得分:4)
fallbackToSystemLocale
不旨在引导您使用locale=null
fallbackToSystemLocale
控制在请求所请求的本地不存在的消息(代码)时要执行的操作 - 或者因为根本没有该语言的消息属性文件,或者仅仅因为消息文件没有不包含消息代码
另一方面,当您使用getMessage
(locale=null
)调用messageSource.getMessage("key", null);
时,区域设置将由Locale.getDefault
org.springframework.context.support.AbstractMessageSource:
protected String getMessageInternal(String code, Object[] args, Locale locale) {
...
if (locale == null) {
locale = Locale.getDefault();
}
...
在考虑fallbackToSystemLocale
财产之前。
最简单的黑客攻击 -arround(这不是一个骇人听闻的问题),会使用你不支持的语言而不是null
:
messageSource.getMessage("key", new Locale("XX"));