spring cloud config 中文乱码

ゞ 浴缸里的玫瑰 2022-05-27 09:36 1139阅读 0赞

在使用 spring cloud config 时,如果在 properties 文件里面有中文的话,会出现乱码。
这里写图片描述

乱码的原因是:spring 默认使用org.springframework.boot.env.PropertiesPropertySourceLoader 来加载配置,底层是通过调用 Properties 的 load 方法,而load方法输入流的编码是 ISO 8859-1

这里写图片描述

解决方法:实现org.springframework.boot.env.PropertySourceLoader 接口,重写 load 方法

  1. public class MyPropertiesHandler implements PropertySourceLoader {
  2. private static final Logger logger = LoggerFactory.getLogger(MyPropertiesHandler.class);
  3. @Override
  4. public String[] getFileExtensions() {
  5. return new String[]{
  6. "properties", "xml"};
  7. }
  8. @Override
  9. public PropertySource<?> load(String name, Resource resource, String profile) throws IOException {
  10. if (profile == null) {
  11. Properties properties = getProperties(resource);
  12. if (!properties.isEmpty()) {
  13. PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource(name, properties);
  14. return propertiesPropertySource;
  15. }
  16. }
  17. return null;
  18. }
  19. private Properties getProperties(Resource resource) {
  20. Properties properties = new Properties();
  21. InputStream inputStream = null;
  22. try {
  23. inputStream = resource.getInputStream();
  24. properties.load(new InputStreamReader(inputStream, "utf-8"));
  25. inputStream.close();
  26. } catch (IOException e) {
  27. logger.error("load inputstream failure...", e);
  28. } finally {
  29. if (inputStream != null) {
  30. try {
  31. inputStream.close();
  32. } catch (IOException e) {
  33. logger.error("close IO failure ....", e);
  34. }
  35. }
  36. }
  37. return properties;
  38. }
  39. }

resources下新建 META-INF 文件夹,新建一个 spring.factories 文件

  1. org.springframework.boot.env.PropertySourceLoader=com.example.configserver.MyPropertiesHandler

重启服务,可以看到中文正常显示了
这里写图片描述

发表评论

表情:
评论列表 (有 0 条评论,1139人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Spring Cloud Config

    为什么要统一管理配置? 1、集中管理 2、不同环境不同配置 3、运行期间动态调整配置 4、自动刷新 简介 Spring Cloud Config为分布式系统外

    相关 spring cloud config

    config,同一配置中心 存在的原因,是为了解决什么问题? 方便配置文件更新,同一配置在git 配置内容安全与权限(即开发不能对项目的配置进行修改) 更