无法使用messageSource解析spring消息代码

我试图在spring连接一个messageSource用于我的应用程序。 它不起作用,给出了这个错误:

org.springframework.context.NoSuchMessageException:在代码’validation_required’下找不到locale’en’的消息。

我的applicationContext.xml包含messageSource的def:

   classpath:messages    

我的消息属性文件位于:

 /WEB-INF/classes/messages/messages_en_US.properties 

最后,我发出的产生错误的调用是:

 String message = messageSource.getMessage("validation_required", null, Locale.ENGLISH); 

这个时候有人能帮助我吗?

问题在于您定义资源包和您指定的语言环境的方式(它们与资源包的搜索顺序不匹配。将您的包重命名为“messages_en.properties”或调用“getMessage(… )“使用新的Locale(”en“,”US“)。我更喜欢第一个选项。

看起来你的道路不正确。 由于您的捆绑包位于/WEB-INF/classes/messages/messages_en_US.properties下,因此您的basename设置应如下所示:classpath:messages / messages(在这种情况下,basename表示路径和属性文件前缀)。

我使用以下bean,它工作正常,但没有指定文件的路径:

    

虽然我使用的文件简称为“messages_en.properties”和“messages_es.properties”,但您可以理解。

你打电话时

  messageSource.getMessage("validation_required", null, null); 

你有例外吗? 尝试使用此文件名messages_en.properties或messages_us_en.properties

试着看一下获取字符串的注释

 package yours; import java.util.Locale; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; /** * * Permet la recuperation des String du LocaleContextHolder hors des jsp * Les langues sont placées dans main/ressources/messagesSources.properties * * Example : new MSG("recuperation_name_invalid").value() * */ @Configurable public class MSG { private String key; @Resource(name = "messageSource") private MessageSource messageSource; public MSG(String key) { super(); this.key = key; } public String value() { Locale locale = LocaleContextHolder.getLocale(); return messageSource.getMessage(key, new Object[0], locale); } @Override public String toString() { return value(); } }