Spring读取properties文件出现乱码的解决方法

来源:互联网 发布:冯大辉丁香园离职知乎 编辑:程序博客网 时间:2024/06/05 05:00

本文为转载文章,原地址文章为:http://blog.csdn.net/yang1982_0907/article/details/44646577

在spring的applicationContext.xml文件中设置和读取properties资源文件时,如果properties文件是UTF-8编码的,并且需要读取的内容包含中文,那么采取默认的property-placeholder标签配置,则读取属性时便会出现乱码!

通过度娘找到很多相似的问题,但几乎都只有一个解决办法,就是使用jdk自带的native2ascii.exe工具,将properties文件中的中文变为编码的形式,若采用这种办法,那么properties文件几乎是没有可读性的!

查阅Spring的官方手册(spring-framework-reference.pdf),发现配置文件中的context:property-placeholder标签对应的是PropertyPlaceholderConfigurer类,再去查Spring的javadoc-api,发现这个类中有一个setFileEncoding方法,可以设置读取properties文件的编码格式,有戏啊!那么context:property-placeholder标签中有没有对应的attribute可以设置呢?再次查阅applicationContext.xml文件针对context:property-placeholder标签的xsd校验文件(spring-context-4.0.xsd),发现propertyPlaceholder元素有个file-encoding属性,于是乎马上用到配置文件中,乱码问题终于解决了!


也就是将原来的:

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <context:property-placeholder location="classpath:*.properties"/>  

修改为:

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <context:property-placeholder location="classpath:*.properties" file-encoding="UTF-8"/>  
0 0
原创粉丝点击