spring cloud config 中文亂碼
阿新 • • 發佈:2018-11-08
原文地址: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
重啟服務,可以看到中文正常顯示了