Spring Boot读取配置文件乱码问题解决

用SpringBoot提供的@Value或者@ConfigurationProperties读取properties配置文件,发现会有中文乱码的问题。

SpringBoot版本为2.0,查看源码,读取配置文件的地方在org.springframework.boot.envPropertiesPropertySourceLoader.loadProperties(Resource resource) 方法(2.0以下有所不同,见文末)

进而找到org.springframework.boot.env.OriginTrackedPropertiesLoader类,关键代码:

//OriginTrackedPropertiesLoade.CharacterReader

CharacterReader(Resource resource) throws IOException {
    this.reader = new LineNumberReader(new InputStreamReader(
        resource.getInputStream(), StandardCharsets.ISO_8859_1));
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这里读取配置文件时,编码写死为ISO_8859_1了。 
解决方案:把这个类copy出来,修改代码为:

//OriginTrackedPropertiesLoade.CharacterReader

CharacterReader(Resource resource) throws IOException {
    this.reader = new LineNumberReader(new InputStreamReader(
        resource.getInputStream(), StandardCharsets.UTF_8));
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

然后把修改后的类放在项目下即可(注意包名需保持一致),这样在加载类的时候,就会只加载我们修改过的,不会加载jar包里面的。


当然还有一种更简单的解决方案,用yml文件代替properties文件,个人觉得yml写起来也蛮爽的。


SpringBoot2.0以下的解决方式有所差异,读取配置的地方在 
org.springframework.core.io.support.PropertiesLoaderUtils.loadProperties(Resource resource) 
主要代码如下:

public static void fillProperties(Properties props, Resource resource) throws IOException {
        InputStream is = resource.getInputStream();
        try {
            String filename = resource.getFilename();
            if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
                props.loadFromXML(is);
            }
            else {
                props.load(is);
            }
        }
        finally {
            is.close();
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

这里直接读取InputStream,修改为从reader读取即可:

public static void fillProperties(Properties props, Resource resource) throws IOException {
        InputStream is = resource.getInputStream();
        InputStreamReader reader = new InputStreamReader(is, "UTF-8");
        try {
            String filename = resource.getFilename();
            if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
                props.loadFromXML(is);
            }
            else {
                props.load(reader);
            }
        }
        finally {
            is.close();
        }
    }

猜你喜欢

转载自blog.csdn.net/white_ice/article/details/80393004