乱码介绍
在使用 spring cloud config 时,如果在 git仓库中的properties 文件里面有中文的话,会出现乱码。
乱码的原因是:spring 默认使用org.springframework.boot.env.PropertiesPropertySourceLoader 来加载配置,底层是通过调用 Properties 的 load 方法,而load方法输入流的编码是 ISO 8859-1
解决方法:
1. 实现org.springframework.boot.env.PropertySourceLoader 接口,重写 load 方法
@Slf4j public class MyPropertiesHandler implements PropertySourceLoader { @Override public String[] getFileExtensions() { return new String[]{"properties", "xml"}; } @Override public List<PropertySource<?>> load(String name, Resource resource) throws IOException { Map<String, ?> properties = loadProperties(resource); if (properties.isEmpty()) { return Collections.emptyList(); } return Collections.singletonList(new OriginTrackedMapPropertySource(name, properties)); } private Map<String, ?> loadProperties(Resource resource) throws IOException { String filename = resource.getFilename(); if (filename != null && filename.endsWith(".xml")) { return (Map) PropertiesLoaderUtils.loadProperties(resource); } return new OriginTrackedPropertiesLoader(resource).load(); } }