SpringCloud|SpringBoot中properties中文乱码解决

1:原因

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

2:解决

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

#地方1

/**
 * properties property source loader and this class load properties file encoding is UTF-8
 *
 * @see org.springframework.boot.env.PropertiesPropertySourceLoader
 **/
@Slf4j
public class PropertiesPropertySourceLoader implements PropertySourceLoader {


    private static final String CHARSET_NAME = "utf-8";

    @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, CHARSET_NAME));
            log.info("properties: {}", properties);
            inputStream.close();
        } catch (IOException e) {
            log.error("load inputstream failure: {}", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("close IO failure: {}", e);
                }
            }
        }
        return properties;
    }
}

#地方2:spring.factories(在src/main/resources建立文件夹META-INF)

org.springframework.boot.env.PropertySourceLoader=\
com.springcloud.config.server.env.PropertiesPropertySourceLoader

#地方3:在application.yml配置http响应编码

spring:
    http:
      encoding:
         #Charset of HTTP requests and responses
         charset: UTF-8
         # Force the encoding to the configured charset on HTTP requests and responses.
         force: true

你可能感兴趣的:(编程语言,spring,乱码)