`
yunzhongxia
  • 浏览: 639933 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Spring获得资源信息报NoSuchMessageException异常解决办法

阅读更多
系统经常把一些配置信息放到一个属性文件中,例如一个config.properties文件内容如下:
db.driver=oracle.jdbc.OracleDriver
db.url=jdbc:oracle:thin:@localhost:1521:hjn
db.user=crddev
db.password=hjn
#jndi\u6570\u636e\u6e90\u914d\u7f6e
db_jndi_name=hjn
db_jndi_url=t3://localhost:7001





 
众所周知,spring已经实现了国际化功能,因此我们可以借助spring现有的功能来获得属性文件中的一个key值。
有时,为了把资源文件分类不直接将properties文件放在src下,例如:src/conf/config.properties。
 需要注入ResourceBundleMessageSource。注意:bean的id必须是messageSource。
 
                 <!-- 资源文件 -->
	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
	          <property name="basenames">
	                      <list>
                                           <value>WEB-INF/classes/conf/config</value>
                                       </list>
	          </property>
	</bean>
 
由于ApplicationContext已经实现了MessageSource接口,因此可以通过下面的代码来获得一个key值。
 
    MessageSource resources = new ClassPathXmlApplicationContext("beans.xml");
    String message = resources.getMessage("db.driver", null, null);
    System.out.println(message);
 
运行上面的程序后报下面的错误:
Exception in thread "main" org.springframework.context.NoSuchMessageException: No message found under code 'db.user' for locale 'null'.
	at org.springframework.context.support.DelegatingMessageSource.getMessage(DelegatingMessageSource.java:65)
	at org.springframework.context.support.AbstractApplicationContext.getMessage(AbstractApplicationContext.java:1192)
	at org.sdp.context.Test.test(Test.java:37)
	at org.sdp.context.Test.main(Test.java:34)
 
很明显,上面的错误是由于没有找到资源文件,原因就在于<value>WEB-INF/classes/conf/config</value>配置错了。正确的配置是
 
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
	<property name="basenames">
	          <list>
                                 <value>conf/config</value>
                          </list>
	</property>
</bean>
  
如果资源文件在src的根目录下直接写上属性文件的名字就可以了,其他的则需要写上类似conf/属性文件 
 
 
 
 
 
 
 
 
 
 
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics