未找到 MessageSource 的 ResourceBundle [消息]:找不到基本名称消息的包

2024-05-20

在 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 文件夹中来避免第一个问题,我需要第二个问题的解决方案,因为我真的不知道那里发生了什么。


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

尝试进行如下操作:

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

重建项目并尝试运行。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

未找到 MessageSource 的 ResourceBundle [消息]:找不到基本名称消息的包 的相关文章

随机推荐