Spring Cloud 配置中心乱码解决

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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值