spring cloud config 中文乱码

 

原文地址:https://blog.csdn.net/sinat_38843093/article/details/79960777

在使用 spring cloud config 时,如果在 properties 文件里面有中文的话,会出现乱码。 
这里写图片描述

乱码的原因是:spring 默认使用org.springframework.boot.env.PropertiesPropertySourceLoader 来加载配置,底层是通过调用 Properties 的 load 方法,而load方法输入流的编码是 ISO 8859-1

这里写图片描述

解决方法:实现org.springframework.boot.env.PropertySourceLoader 接口,重写 load 方法

public class MyPropertiesHandler implements PropertySourceLoader {

    private static final Logger logger = LoggerFactory.getLogger(MyPropertiesHandler.class);

    @Override
    public String[] getFileExtensions() {
        return new String[]{"properties", "xml"};
    }

    @Override
    public PropertySource<?> load(String name, Resource resource, String profile) throws IOException {
        if (profile == null) {
            Properties properties = getProperties(resource);
            if (!properties.isEmpty()) {
                PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource(name, properties);
                return propertiesPropertySource;
            }
        }
        return null;
    }

    private Properties getProperties(Resource resource) {
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = resource.getInputStream();
            properties.load(new InputStreamReader(inputStream, "utf-8"));
            inputStream.close();
        } catch (IOException e) {
            logger.error("load inputstream failure...", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("close IO failure ....", e);
                }
            }
        }
        return properties;
    }
}

在 resources下新建 META-INF 文件夹,新建一个 spring.factories 文件

org.springframework.boot.env.PropertySourceLoader=com.example.configserver.MyPropertiesHandler
  •  

重启服务,可以看到中文正常显示了 
这里写图片描述

猜你喜欢

转载自blog.csdn.net/hhj13978064496/article/details/82698766