在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();
}
}
我有两个问题:
问题1: 我的消息文件位于WEB-INF / i18n目录下。它只包含2个文件:messages_en.properties和messages_hr.properties。
如果我尝试运行上面的代码,我会收到警告: “找不到MessageSource的ResourceBundle [messages]:找不到基本名称消息的bundle,locale'some locale'”,后跟NullPointerException。
如果我将消息文件移动到WEB-INF / classes文件夹,问题就会消失,但是我遇到第二个问题。
问题2: 如果我在消息在WEB-INF / classes目录下运行上面的代码我得到异常:“在代码'some.code'下找不到用于locale'some locale'的消息”,即使你所有的密钥都被正确加载。
问题是:如何通过将消息保存在WEB-INF / i18n文件夹中来避免问题1,我需要第2个问题的解决方案,因为我真的不知道那里发生了什么。
答案 0 :(得分:7)
您可能只需要将资源文件夹添加到项目的类路径中。
尝试执行以下操作:
在Package Explorer视图中右键单击项目名称---&gt;属性---&gt; Java构建路径---&gt;留在Source选项卡(默认打开)---&gt;点击文件夹---&gt;现在应该出现项目中所有文件夹的列表---&gt;勾选包含消息属性文件的文件夹
重建项目并尝试运行。
答案 1 :(得分:1)
虽然问题已经过去了2年,但我遇到了同样的问题并找到了解决方案。
如果要将i18n属性文件保留在webcontent文件夹之外的某个位置,则应修改.setting
文件夹中的文件org.eclipse.resources.prefs。并且这样做:
eclipse.preferences.version=1
encoding//WebContent/WEB-INF/i18n/property_en.properties=UTF-8
encoding//WebContent/WEB-INF/i18n/property_fr.properties=UTF-8
在bean属性中,像以前一样设置messageSource。但是补充说:
<property name="defaultEncoding" value="UTF-8" />
希望它有效。