[已解决] 从Spring Boot项目的application.properties获取属性值乱码
项目场景
Spring Boot 2.4
问题描述
Spring Boot项目的代码逻辑中,从application.properties获取到的属性值显示乱码
原因分析
因为spring boot项目默认
的加载application.properties配置文件是通过字符集StandardCharsets.ISO_8859_1
载入的。
相关代码在 org.springframework.boot.env.OriginTrackedPropertiesLoader
类中,具体代码片段如下:
/**
* Reads characters from the source resource, taking care of skipping comments,
* handling multi-line values and tracking {@code ''} escapes.
*/
private static class CharacterReader implements Closeable {
private static final String[] ESCAPES = { "trnf", "trnf" };
private final LineNumberReader reader;
private int columnNumber = -1;
private boolean escaped;
private int character;
private boolean lastLineComment;
CharacterReader(Resource resource) throws IOException {
this.reader = new LineNumberReader(
new InputStreamReader(resource.getInputStream(), StandardCharsets.ISO_8859_1));
}
解决方案
方案一
根据上面的分析,可以使用下面的方法,原理:
创建同包同名的类,可以直接覆盖掉jar包中的类,spring项目会优先加载自定义的类
- 在自己的项目里,src/main/java 下创建一个同名的package:org.springframework.boot.env
- 定位到
org.springframework.boot.env.OriginTrackedPropertiesLoader
类,将这个类copy到上面新建的package里 - 在上面步骤复制好的类里,修改上面指定字符集的代码,如下:
/**
* Reads characters from the source resource, taking care of skipping comments,
* handling multi-line values and tracking {@code ''} escapes.
*/
private static class CharacterReader implements Closeable {
private static final String[] ESCAPES = { "trnf", "trnf" };
private final LineNumberReader reader;
private int columnNumber = -1;
private boolean escaped;
private int character;
private boolean lastLineComment;
CharacterReader(Resource resource) throws IOException {
this.reader = new LineNumberReader(
new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF-8));
}
- 编译项目,再启动,即可解决。
方案二
将汉字转为Unicode码,再存入配置文件,即可解决。
原理:
几乎 java 中所有汉字乱码问题都可以用 unicode 编码 来解决
工具:菜鸟工具
方案三
将application.properties改为application.yml。
相对于 .properties文件,.yml文件要友好的多,正常使用的话,应该是不存在汉字乱码问题。
方案四
创建一个新的properties配置文件,例如:demo.properties,设置文件编码格式为UTF-8。
引入配置并指定字符集,注意:这种方式针对application.properties是不行的。
添加下面的代码到启动类或者需要的类上:
@PropertySource(value = "classpath:demo.properties",encoding = "UTF-8")
例如:
@Component
@ConfigurationProperties(prefix = "demo")
@PropertySource(value = "classpath:demo.properties",encoding = "UTF-8")
@Getter
@Setter
public class DemoProperties {
...
}
扩展:
Spring 4.3 通过引入 PropertySourceFactory 接口。
PropertySourceFactory 是PropertySource 的工厂类。默认实现是 DefaultPropertySourceFactory,可以构造ResourcePropertySource 实例。
@PropertySource 注解有一个 factory 属性,通过这个属性来注入 PropertySourceFactory。
扩展
如果 通过 nacos 来加载 yml 配置,汉字会出现乱码,甚至导致 nacos 不能启动。使用 unicode 的方式解决。
如果是 nacos 中加载配置文件,只要有汉字就会出错,因此,注释信息也尽量移除。