在 applicationContext.xml 中,我定义了 MessageSource,如下所示:
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>/WEB-INF/i18n/messages</value>
</list>
</property>
</bean>
我还需要加载所有本地化消息,因此我为其创建了自己的类:
public class ErpMessageSource extends ResourceBundleMessageSource {
public Map<String, String> getMessages(String basename, Locale locale) {
Set<String> keys = getKeys(basename, locale);
Map<String, String> m = new HashMap<String, String>();
for (String key : keys) {
try {
m.put(key, getMessage(key, null, locale));
} catch (Exception e) {
System.err.println(key + " - " + e.getLocalizedMessage());
}
}
return m;
}
private Set<String> getKeys(String basename, Locale locale) {
ResourceBundle bundle = getResourceBundle(basename, locale);
return bundle.keySet();
}
}
我有两个问题:
问题一:我的消息文件位于 WEB-INF/i18n 目录下。它仅包含 2 个文件:messages_en.properties 和 messages_hr.properties。
如果我尝试运行上面的代码,我会收到警告:
“未找到 MessageSource 的 ResourceBundle [消息]:找不到基本名称消息的包,区域设置“某些区域设置””,后跟 NullPointerException。
如果我将消息文件移动到 WEB-INF/classes 文件夹,问题就会消失,但我遇到了第二个问题。
问题2:如果我在消息位于 WEB-INF/classes 目录下时运行上面的代码,我会收到异常:“在语言环境‘某些语言环境’的代码‘some.code’下找不到消息”,即使所有键都已正确加载。
问题是:如何通过将消息保留在 WEB-INF/i18n 文件夹中来避免第一个问题,我需要第二个问题的解决方案,因为我真的不知道那里发生了什么。