背景:
JDK 11
IDEA 2021.3
SpringBoot 2.5.6
重现问题
解决方案
1)使用application.yml来保存你的配置,效果和application.properties一样,配置更直观(推荐)
2)使用@PropertySource(value=“classpath:xxx.properties”, encoding=“UTF-8”)注解,自定义配置文件,相信大家想要的肯定不是这种
3)打开IDEA设置,将这里的编码选择为UTF-8并且勾选Transparent native-to-ascii conversion,这里是*.properties文件使用UTF-8格式,存储中文使用ASCII码,你在IDEA中看中文是正常的,使用文本工具打开中文是一串ASCII码
小结:设置编码是解决不了问题的,开发中尽量还是不要在配置文件中使用中文
问题分析
- *.properties默认使用ISO-8859-1编码加载
- *.yml/*.yaml默认使用UTF-8编码加载
一路跟踪到Springboot加载配置文件的地方org.springframework.boot.context.config.ConfigFileApplicationListener.Loader#loadDocuments,这个类从从Springboot2.4.0开始不推荐使用,直到Springboot2.6.0废弃,不扯远了,该类方法源码是这样的
private List<Document> loadDocuments(PropertySourceLoader loader, String name, Resource resource)
throws IOException {
DocumentsCacheKey cacheKey = new DocumentsCacheKey(loader, resource);
List<Document> documents = this.loadDocumentsCache.get(cacheKey);
if (documents == null) {
List<PropertySource<?>> loaded = loader.load(name, resource);
documents = asDocuments(loaded);
this.loadDocumentsCache.put(cacheKey, documents);
}
return documents;
}
很显然,关键点就在loader.load(name, resource)这里,他有两个实现类