乱码介绍

在使用 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();
    }
}
View Code

相关文章:

  • 2021-05-13
  • 2021-08-11
  • 2021-05-15
  • 2022-12-23
  • 2021-06-24
  • 2021-07-17
  • 2022-12-23
猜你喜欢
  • 2021-11-17
  • 2021-08-20
  • 2021-11-08
  • 2022-12-23
  • 2021-07-19
  • 2022-03-04
相关资源
相似解决方案