**
Spring Cloud 配置中心中文乱码问题解决
**
参考文章:https://blog.csdn.net/fan521dan/article/details/105084260
pom配置:org.springframework.boot spring-boot-starter-parent 2.3.3.RELEASE
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR8</spring-cloud.version>
</properties>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
乱码原因:spring 默认使用 org.springframework.boot.env.PropertiesPropertySourceLoader 来加载配置,底层是通过调用 Properties 的 load 方法,而load方法输入流的编码是 ISO 8859-1 ,所以会出现中文乱码问题
解决路劲:
- 解决步骤:
1.自定义属性源加载器,实现 PropertySourceLoader 接口
2.在 resources 文件夹下,创建 META-INF 文件夹,再创建 spring.factories 文件
3.application.properties中增加配置
一、自定义属性源加载器:
public class CustomPropertySourceLoader implements PropertySourceLoader {
private static final Logger logger = LoggerFactory.getLogger(CustomPropertySourceLoader.class);
@Override
public String[] getFileExtensions() {
return new String[]{"properties", "xml"};
}
@Override
public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
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();
try (InputStream inputStream = resource.getInputStream();){
properties.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
inputStream.close();
} catch (IOException e) {
logger.error("load inputstream failure...", e);
}
return (Map) properties;
}
}
二、 spring.factories 中指定属性源加载器:
org.springframework.boot.env.PropertySourceLoader=com.example.configserver.CustomPropertySourceLoader
三、application.properties中增加配置
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force=true
server.servlet.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8
版权声明:本文为weixin_42941199原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。