2

在 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]:找不到基本名称消息的捆绑包,语言环境‘某些语言环境’”,然后是 NullPointerException。

如果我将消息文件移动到 WEB-INF/classes 文件夹,问题就消失了,但是我遇到了第二个问题。

问题 2: 如果我在消息位于 WEB-INF/classes 目录下时运行上面的代码,我会收到异常:“在代码 'some.code' 下找不到任何消息,用于区域设置 'some locale'”,即使所有键都已正确加载.

问题是:如何通过将消息保存在 WEB-INF/i18n 文件夹中来避免问题 1,我需要解决第二个问题,因为我真的不知道那里发生了什么。

4

2 回答 2

8

您可能只需要将资源文件夹添加到项目的类路径中。

尝试执行以下操作:

右键单击 Package Explorer 视图中的项目名称---> Properties ---> Java Build Path ---> 停留在 Source 选项卡(默认打开)---> 单击 Folder ---> 列表现在应该出现项目中的所有文件夹 ---> 在包含消息属性文件的文件夹上打勾

重建项目并尝试运行。

于 2012-12-07T10:24:02.460 回答
1

虽然问这个问题已经2年了,但我遇到了同样的问题并找到了解决方案。

如果要将 i18n 属性文件保存在 webcontent 文件夹之外的某个位置,则应修改该文件夹中的 org.eclipse.resources.prefs.setting文件。并这样做:

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" />

希望它有效。

于 2014-05-27T14:26:54.763 回答