我正在尝试在spring中连接一个messageSource以用于我的应用程序。它不起作用,给出了这个错误:
org.springframework.context.NoSuchMessageException:在代码'validation_required'下找不到区域设置'en'的消息。
我的 applicationContext.xml 包含messageSource的这个def:
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:messages</value>
</list>
</property>
</bean>
我的消息属性文件位于:
/WEB-INF/classes/messages/messages_en_US.properties
最后,我发出的产生错误的电话是:
String message = messageSource.getMessage("validation_required", null, Locale.ENGLISH);
这个时候有人可以帮助我吗?
答案 0 :(得分:4)
似乎你的道路不正确。 既然您的包在/WEB-INF/classes/messages/messages_en_US.properties下,您的基本名称设置应如下所示:classpath:messages / messages(在这种情况下,basename表示路径和属性文件前缀)。
答案 1 :(得分:3)
问题在于您定义资源包和您指定的语言环境的方式(它们与资源包的search order不匹配。要么将包重命名为“messages_en.properties”或调用“getMessage(...)”使用新的Locale(“en”,“US”)。我更喜欢第一个选项。
答案 2 :(得分:2)
我使用以下bean并且它正常工作而没有指定文件的路径:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" abstract="false"
scope="singleton" lazy-init="default">
<property name="basename" value="messages"/>
</bean>
虽然我使用的文件简称为“messages_en.properties”和“messages_es.properties”,但您可以理解。
致电时
messageSource.getMessage("validation_required", null, null);
你有例外吗?尝试使用此文件名messages_en.properties或messages_us_en.properties
答案 3 :(得分:0)
试试这个 查看获取字符串的注释
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();
}
}