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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章