`

无聊的传递水桶:Spring国际化时报NoSuchMessageException

 
阅读更多

用Spring ResourceBundle时,抛了异常:
org.springframework.context.NoSuchMessageException: No message found under code 'userlogin' for locale 'zh_CN'.
at org.springframework.context.support.DelegatingMessageSource.getMessage(DelegatingMessageSource.java:65)
at org.springframework.context.support.AbstractApplicationContext.getMessage(AbstractApplicationContext.java:646)

经过网搜,清一色的转帖解决方案:

写道
这样的错误。
总结一下,有可能由以下原因造成:
1.如果你使用eclipse创建的工程是class和src分开的,那么资源属性文件一定要放在src目录以内。
2.属性文件名的写法:
messages_zh_CN.properties (中文)
messages_en_US.properties (英文)
3.配置messageSource这个bean(注意:一定是messageSource不是messageResource ,这是Spring规定的)
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>messages</value>
</list>
</property>
</bean>
注意以上问题,就OK了。

 其实,上面的解决方案纯属瞎扯淡:
1.资源文件放在哪里,鬼才管你,爱放哪里放哪里,只要用时找的到;
2.资源文件命名规则的本质是:(你的资源文件可以是任意你喜欢的,比如msgResource)
     2.1 msgResource.properties 找不到对应的Locale时;
     2.2 msgResource_zh_CN.properties Locale为中文时;
     2.3 msgResource_en_US.propertise Locale为英文时;
     。。。支持其它语言请自行网搜,否则,就采用默认的msgResource.properties;
3.Spring Bean的id爱起啥名起啥名,鬼才管你。

那上面所说的异常到底是如何引起的呢?很简单,加载的资源文件位置不对。

下面是一个正确的样例(抛砖引玉,相信您看到懂):

<bean id="msgResource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
         <property name="basenames">
             <list>
			 <value>classpath:msg/yyTips</value>
			 <value>classpath:msg/ipTips</value>
	    </list>
         </property>
         <property name="cacheSeconds" value="-1"/>
    </bean>
    
    在msg目录下的资源文件有:
    yyTips.properties、yyTips_zh_CN.properties、yyTips_en_US.properties,可以根据需要加载其它语言支持

 

    顺便提及一下,get时出现中文乱码时,应当如何解决?
    最快、最直接的方法是用PropertiesEditor编辑属性文件,并将属性文件设置为ISO-8859-1编码,以便确保有效的将中文转为Unicode编码。
   
    附PropertiesEditor地址:http://propedit.sourceforge.jp/eclipse/updates/,至于eclipse安装该插件的方法,请自行网搜,很简单的。

1
3
分享到:
评论
3 楼 redsnow_fenglin 2016-11-03  
3.Spring Bean的id爱起啥名起啥名,鬼才管你。

解释下这句话对大家造成的误解:

1)“鬼才管你”,产生于当时环境的背景下,是针对无聊传递水桶中提到的bean命名上有要求而言的,故“鬼才管你”;

2)“鬼要管你”,这个是规范的问题,耳熟能详的是“命名要望文生义”“遵循约定便沟通维护”“约定优于配置”...,故“鬼要管你”;
2 楼 yyg329405 2012-11-06  
1.如果你使用eclipse创建的工程是class和src分开的,那么资源属性文件一定要放在src目录以内。

这句话,解决了!
1 楼 atgfss 2012-10-29  
引用

3.Spring Bean的id爱起啥名起啥名,鬼才管你。

Spring 的官方文档中这样写的:

When an ApplicationContext is loaded, it automatically searches for a MessageSource bean defined in the context. The bean must have the name messageSource. If such a bean is found, all calls to the preceding methods are delegated to the message source. If no message source is found, the ApplicationContext attempts to find a parent containing a bean with the same name. If it does, it uses that bean as the MessageSource. If the ApplicationContext cannot find any source for messages, an empty DelegatingMessageSource is instantiated in order to be able to accept calls to the methods defined above.

相关推荐

Global site tag (gtag.js) - Google Analytics