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));
}

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

//OriginTrackedPropertiesLoade.CharacterReader

CharacterReader(Resource resource) throws IOException {
    this.reader = new LineNumberReader(new InputStreamReader(
        resource.getInputStream(), StandardCharsets.UTF_8));
}

然后把修改后的类放在项目下即可(注意包名需保持一致),这样在加载类的时候,就会只加载我们修改过的,不会加载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();
        }
    }

这里直接读取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();
        }
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值