1. springboot 2.X 版本 cloud的配置中心中文乱码解决
乱码原因:
spring 默认使用org.springframework.boot.env.PropertiesPropertySourceLoader 来加载配置,底层是通过调用 Properties 的 load 方法,而load方法输入流的编码是 ISO-8859-1。
网上的解决办法,在配置中心自定义类实现PropertySourceLoader:
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 List<PropertySource<?>> load(String name, Resource resource) throws IOException {
/*List<PropertySource<?>> propertySourceList = new ArrayList<PropertySource<?>>();
Properties properties = getProperties(resource);
if (!properties.isEmpty()) {
PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource(name, properties);
propertySourceList.add(propertiesPropertySource);
}
return propertySourceList;*/
Map<String, ?> properties = loadProperties(resource);
if (properties.isEmpty()) {
return Collections.emptyList();
}
return Collections
.singletonList(new OriginTrackedMapPropertySource(name, properties));
}
private Map<String, ?> loadProperties(Resource resource) {
Properties properties = new Properties();
InputStream inputStream = null;
try {
inputStream = resource.getInputStream();
properties.load(new InputStreamReader(inputStream, StandardCharsets.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 (Map) properties;
}
}
2.在 resources下创建 META-INF 目录 并在目录下创建spring.factories文件
文件内容:org.springframework.boot.env.PropertySourceLoader=com.spring.config.MyPropertiesHandler
(你的自定类路径)
但本人按此照此方法配置依旧乱码。
最终解决办法:
String str = new String(str.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);