Springboot-application.properties编码问题
设置application.properties为utf-8
UTF-8,这样在windows和linux服务器中查看配置文件都能正常显示中文。否则可能中文无法正常显示。
application.properties中配置如下:
demo.to-who=张三
读取配置的中文
@RestController
public class TestController {
@Value("${demo.to-who}")
private String toWho;
@RequestMapping("/test2")
public Object test2() throws UnsupportedEncodingException {
System.out.println(toWho);
System.out.println(new String(toWho.getBytes("iso8859-1")));
System.out.println(new String(toWho.getBytes("iso8859-1"), "utf-8"));
return null;
}
}
结果打印
需要将数据编码从iso8859-1转为utf-8才可正常使用。
å¼ ä¸‰
张三
张三
分析
源码中
private static class CharacterReader implements Closeable {
// 其他代码省略
CharacterReader(Resource resource) throws IOException {
this.reader = new LineNumberReader(new InputStreamReader(
resource.getInputStream(), StandardCharsets.ISO_8859_1));
}
// 其他代码省略
}
也就是说不论application.properties文件被设置为哪种编码格式,最终还是以ISO-8859-1的编码格式进行加载。
而yml/yaml默认以UTF-8加载;