springcloud config中文乱码问题
2020-12-13 06:24
标签:spro 显示 puts tomcat 解决 ror conf enabled env 摘录一段网上盛传的,如下: 在使用 spring cloud config 时,如果在 properties 文件里面有中文的话,会出现乱码。 解决方法:实现org.springframework.boot.env.PropertySourceLoader 接口,重写 load 方法 public class MyPropertiesHandler implements PropertySourceLoader { private static final Logger logger = LoggerFactory.getLogger(MyPropertiesHandler.class); @Override @Override private Properties getProperties(Resource resource) { org.springframework.boot.env.PropertySourceLoader=com.example.configserver.MyPropertiesHandler --------------------------------------------------------华丽的分割线----------------------------------------------------------- 尝试各种方法都没有解决,深受其害,查了近一天, 有的说springcloud1.* 和2.*有不同的写法,等等,不一一细说,讲一下最终解决方案。 springcloud Finchley.RELEASE 对应的 springboot-2.0.4 主要是springboot框架中env包下OriginTrackedPropertiesLoader类,159行,有一个ISO8859-1的编码。 1.我们要做的是将spring框架中的源码复制到项目中,目录和源码中保持一致。 2.application.yaml中 增加如下配置: server.tomcat.uri-encoding=utf-8 spring.http.encoding.charset=utf-8 spring.http.encoding.enabled=true spring.http.encoding.force=true 大功告成,但愿能拯救水深火热的广大猿友! springcloud config中文乱码问题 标签:spro 显示 puts tomcat 解决 ror conf enabled env 原文地址:https://www.cnblogs.com/xifenglou/p/11177581.html
乱码的原因是:spring 默认使用org.springframework.boot.env.PropertiesPropertySourceLoader 来加载配置,底层是通过调用 Properties 的 load 方法,而load方法输入流的编码是 ISO 8859-1
public String[] getFileExtensions() {
return new String[]{"properties", "xml"};
}
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;
}
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 文件
1
重启服务,可以看到中文正常显示了