问题,springcloud config-server服务配置git 存储文件中有包含中文,读取属性文件以后,出现乱码!!

    git仓库中的属性文件名 locale_cn.properties

    如下所示

    shine.login.test=测试项目
    shine.login.abc=终于来个Ok
    

    请求 http://localhost:8769/locale/cn

    出现乱码。




    解决:

    1,加载属性文件类,重写

    OriginTrackedPropertiesLoader类。

    2,自己定义加载属性文件

    我采用,自己定义加载属性文件

    具体如下:

      

    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 = this.loadProperties(resource);
            return properties.isEmpty() ? Collections.emptyList() : Collections.singletonList(new OriginTrackedMapPropertySource(name, properties));
        }
    
        private Map<String, ?> loadProperties(Resource resource) throws IOException {
            String filename = resource.getFilename();
            return (Map) (filename != null && filename.endsWith(".xml") ? PropertiesLoaderUtils.loadProperties(resource) : loadPro(resource));
        }
    
        
        private Map<String, ?> loadPro(Resource resource) {
            Map<String, String> proMap = new HashMap<>();
            try {
                InputStream inputStream = resource.getInputStream();
                List<Byte> byteList = new LinkedList<Byte>();
                byte[] readByte = new byte[1024];
                int length;
                while ((length = inputStream.read(readByte)) > 0) {
                    for (int i = 0; i < length; i++) {
                        byteList.add(readByte[i]);
                    }
                }
                byte[] allBytes = new byte[byteList.size()];
                int index = 0;
                for (Byte soloByte : byteList) {
                    allBytes[index] = soloByte;
                    index += 1;
                }
                String str = new String(allBytes, "UTF-8");
                String[] strs = StringUtils.splitByWholeSeparator(str, "\n");
                for (String tmp_str : strs) {
                    if (StringUtils.isNotBlank(tmp_str)) {
                        String[] tmpstr = StringUtils.splitByWholeSeparator(tmp_str, "=");
                        proMap.put(tmpstr[0], tmpstr[1]);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return proMap;
    
        }
    }
    

     

    同时,增加配置在 src/resources目录下增加文件夹

    META-INF/spring.factories

    添加一行代码 

    org.springframework.boot.env.PropertySourceLoader=com.shine.configserver.MyPropertiesHandler

     

    重启应用,再刷新 http://localhost:8769/locale/cn 即可看到正确的

     

     

     

     

     

     

     

     

     


     

     
















    联系QQ:343886028 --加QQ群 145315854