广告
返回顶部
首页 > 资讯 > 后端开发 > Python >解决Springboot-application.properties中文乱码问题
  • 473
分享到

解决Springboot-application.properties中文乱码问题

2024-04-02 19:04:59 473人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录SpringBoot-application.properties中文乱码设置application.properties为utf-8读取配置的中文结果打印分析springboo

Springboot-application.properties中文乱码

Springboot-application.properties编码问题 设置application.properties为utf-8读取配置的中文结果打印分析

设置application.properties为utf-8

UTF-8,这样在windowslinux服务器中查看配置文件都能正常显示中文。否则可能中文无法正常显示。

在这里插入图片描述

application.properties中配置如下:


demo.to-who=张三

读取配置的中文


@RestController
public class TestController {
    @Value("${demo.to-who}")
    private String toWho;
    @RequestMapping("/test2")
    public Object test2() throws UnsupportedEncodingException {
        System.out.println(toWho);
        System.out.println(new String(toWho.getBytes("iso8859-1")));
        System.out.println(new String(toWho.getBytes("iso8859-1"), "utf-8"));
        return null;
    }
}

结果打印

需要将数据编码从iso8859-1转为utf-8才可正常使用。

å¼ ä¸‰

张三

张三

分析

源码


private static class CharacterReader implements Closeable {
    // 其他代码省略
    CharacterReader(Resource resource) throws IOException {
      this.reader = new LineNumberReader(new InputStreamReader(
          resource.getInputStream(), StandardCharsets.ISO_8859_1));
    }
    // 其他代码省略
}

也就是说不论application.properties文件被设置为哪种编码格式,最终还是以ISO-8859-1的编码格式进行加载。

而yml/yaml默认以UTF-8加载

Springboot配置文件application.properties支持中文

版本说明

本文不完全基于springboot-2.4.5,各版本需要重写类的逻辑各有不同,本文的代码只可模仿,不可复制

为什么不支持中文

PropertySourceLoader接口

先看读取配置文件的接口 org.springframework.boot.env.PropertySourceLoader

在这里插入图片描述

Strategy interface located via {@link SpringFactoriesLoader} and used to load a {@link PropertySource}.

意思是说通过META-INF/spring.factories配置文件加载

在这里插入图片描述

在这里插入图片描述

PropertiesPropertySourceLoader类

接口 org.springframework.boot.env.PropertySourceLoader下有两个默认实现

在这里插入图片描述

org.springframework.boot.env.YamlPropertySourceLoader负责读取yml文件,

org.springframework.boot.env.PropertiesPropertySourceLoader负责读取properties和xml文件

在这里插入图片描述

OriginTrackedPropertiesLoader类

可以看出org.springframework.boot.env.OriginTrackedPropertiesLoader.CharacterReader类

在这里插入图片描述

以ISO_8859_1编码方式读取properties文件

重写读取application.properties文件的逻辑

使SpringBoot配置文件application.properties支持中文

1.创建OriginTrackedPropertiesLoader文件

复制org.springframework.boot.env.OriginTrackedPropertiesLoader文件内容,并修改ISO_8859_1编码为UTF_8编码


package com.xxx.config;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.NIO.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BooleanSupplier;
import org.springframework.boot.origin.Origin;
import org.springframework.boot.origin.OriginTrackedValue;
import org.springframework.boot.origin.TextResourceOrigin;
import org.springframework.boot.origin.TextResourceOrigin.Location;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

public class MyOriginTrackedPropertiesLoader {
	private final Resource resource;
	
	MyOriginTrackedPropertiesLoader(Resource resource) {
		Assert.notNull(resource, "Resource must not be null");
		this.resource = resource;
	}
	
	List<Document> load() throws IOException {
		return load(true);
	}
	
	List<Document> load(boolean expandLists) throws IOException {
		List<Document> documents = new ArrayList<>();
		Document document = new Document();
		StringBuilder buffer = new StringBuilder();
		try (CharacterReader reader = new CharacterReader(this.resource)) {
			while (reader.read()) {
				if (reader.isPoundCharacter()) {
					if (isNewDocument(reader)) {
						if (!document.isEmpty()) {
							documents.add(document);
						}
						document = new Document();
					}
					else {
						if (document.isEmpty() && !documents.isEmpty()) {
							document = documents.remove(documents.size() - 1);
						}
						reader.setLastLineComment(true);
						reader.skipComment();
					}
				}
				else {
					reader.setLastLineComment(false);
					loadKeyAndValue(expandLists, document, reader, buffer);
				}
			}
		}
		if (!document.isEmpty() && !documents.contains(document)) {
			documents.add(document);
		}
		return documents;
	}
	private void loadKeyAndValue(boolean expandLists, Document document, CharacterReader reader, StringBuilder buffer)
			throws IOException {
		String key = loadKey(buffer, reader).trim();
		if (expandLists && key.endsWith("[]")) {
			key = key.substring(0, key.length() - 2);
			int index = 0;
			do {
				OriginTrackedValue value = loadValue(buffer, reader, true);
				document.put(key + "[" + (index++) + "]", value);
				if (!reader.isEndOfLine()) {
					reader.read();
				}
			}
			while (!reader.isEndOfLine());
		}
		else {
			OriginTrackedValue value = loadValue(buffer, reader, false);
			document.put(key, value);
		}
	}
	private String loadKey(StringBuilder buffer, CharacterReader reader) throws IOException {
		buffer.setLength(0);
		boolean previousWhitespace = false;
		while (!reader.isEndOfLine()) {
			if (reader.isPropertyDelimiter()) {
				reader.read();
				return buffer.toString();
			}
			if (!reader.isWhiteSpace() && previousWhitespace) {
				return buffer.toString();
			}
			previousWhitespace = reader.isWhiteSpace();
			buffer.append(reader.getCharacter());
			reader.read();
		}
		return buffer.toString();
	}
	private OriginTrackedValue loadValue(StringBuilder buffer, CharacterReader reader, boolean splitLists)
			throws IOException {
		buffer.setLength(0);
		while (reader.isWhiteSpace() && !reader.isEndOfLine()) {
			reader.read();
		}
		Location location = reader.getLocation();
		while (!reader.isEndOfLine() && !(splitLists && reader.isListDelimiter())) {
			buffer.append(reader.getCharacter());
			reader.read();
		}
		Origin origin = new TextResourceOrigin(this.resource, location);
		return OriginTrackedValue.of(buffer.toString(), origin);
	}
	private boolean isNewDocument(CharacterReader reader) throws IOException {
		if (reader.isLastLineComment()) {
			return false;
		}
		boolean result = reader.getLocation().getColumn() == 0 && reader.isPoundCharacter();
		result = result && readAndExpect(reader, reader::isHyphenCharacter);
		result = result && readAndExpect(reader, reader::isHyphenCharacter);
		result = result && readAndExpect(reader, reader::isHyphenCharacter);
		if (!reader.isEndOfLine()) {
			reader.read();
			reader.skipWhitespace();
		}
		return result && reader.isEndOfLine();
	}
	private boolean readAndExpect(CharacterReader reader, BooleanSupplier check) throws IOException {
		reader.read();
		return check.getAsBoolean();
	}
	
	private static class CharacterReader implements Closeable {
		private static final String[] ESCAPES = { "trnf", "\t\r\n\f" };
		private final LineNumberReader reader;
		private int columnNumber = -1;
		private boolean escaped;
		private int character;
		private boolean lastLineComment;
		CharacterReader(Resource resource) throws IOException {
			this.reader = new LineNumberReader(
					new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8));
		}
		@Override
		public void close() throws IOException {
			this.reader.close();
		}
		boolean read() throws IOException {
			return read(false);
		}
		boolean read(boolean wrappedLine) throws IOException {
			this.escaped = false;
			this.character = this.reader.read();
			this.columnNumber++;
			if (this.columnNumber == 0) {
				skipWhitespace();
				if (!wrappedLine) {
					if (this.character == '!') {
						skipComment();
					}
				}
			}
			if (this.character == '\\') {
				this.escaped = true;
				readEscaped();
			}
			else if (this.character == '\n') {
				this.columnNumber = -1;
			}
			return !isEndOfFile();
		}
		private void skipWhitespace() throws IOException {
			while (isWhiteSpace()) {
				this.character = this.reader.read();
				this.columnNumber++;
			}
		}
		private void setLastLineComment(boolean lastLineComment) {
			this.lastLineComment = lastLineComment;
		}
		private boolean isLastLineComment() {
			return this.lastLineComment;
		}
		private void skipComment() throws IOException {
			while (this.character != '\n' && this.character != -1) {
				this.character = this.reader.read();
			}
			this.columnNumber = -1;
		}
		private void readEscaped() throws IOException {
			this.character = this.reader.read();
			int escapeIndex = ESCAPES[0].indexOf(this.character);
			if (escapeIndex != -1) {
				this.character = ESCAPES[1].charAt(escapeIndex);
			}
			else if (this.character == '\n') {
				this.columnNumber = -1;
				read(true);
			}
			else if (this.character == 'u') {
				readUnicode();
			}
		}
		private void readUnicode() throws IOException {
			this.character = 0;
			for (int i = 0; i < 4; i++) {
				int digit = this.reader.read();
				if (digit >= '0' && digit <= '9') {
					this.character = (this.character << 4) + digit - '0';
				}
				else if (digit >= 'a' && digit <= 'f') {
					this.character = (this.character << 4) + digit - 'a' + 10;
				}
				else if (digit >= 'A' && digit <= 'F') {
					this.character = (this.character << 4) + digit - 'A' + 10;
				}
				else {
					throw new IllegalStateException("MalfORMed \\uxxxx encoding.");
				}
			}
		}
		boolean isWhiteSpace() {
			return !this.escaped && (this.character == ' ' || this.character == '\t' || this.character == '\f');
		}
		boolean isEndOfFile() {
			return this.character == -1;
		}
		boolean isEndOfLine() {
			return this.character == -1 || (!this.escaped && this.character == '\n');
		}
		boolean isListDelimiter() {
			return !this.escaped && this.character == ',';
		}
		boolean isPropertyDelimiter() {
			return !this.escaped && (this.character == '=' || this.character == ':');
		}
		char getCharacter() {
			return (char) this.character;
		}
		Location getLocation() {
			return new Location(this.reader.getLineNumber(), this.columnNumber);
		}
		boolean isPoundCharacter() {
			return this.character == '#';
		}
		boolean isHyphenCharacter() {
			return this.character == '-';
		}
	}
	
	static class Document {
		private final Map<String, OriginTrackedValue> values = new LinkedHashMap<>();
		void put(String key, OriginTrackedValue value) {
			if (!key.isEmpty()) {
				this.values.put(key, value);
			}
		}
		boolean isEmpty() {
			return this.values.isEmpty();
		}
		Map<String, OriginTrackedValue> asMap() {
			return this.values;
		}
	}
}

2.创建PropertiesPropertySourceLoader文件

复制org.springframework.boot.env.PropertiesPropertySourceLoader文件内容,并将调用org.springframework.boot.env.OriginTrackedPropertiesLoader类改为调用com.xxx.config.MyOriginTrackedPropertiesLoader


package com.xxx.config;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import com.xxx.config.MyOriginTrackedPropertiesLoader.Document;

public class MyPropertiesPropertySourceLoader implements PropertySourceLoader {
	private static final String XML_FILE_EXTENSION = ".xml";
	@Override
	public String[] getFileExtensions() {
		return new String[] { "properties", "xml" };
	}
	@Override
	public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
		List<Map<String, ?>> properties = loadProperties(resource);
		if (properties.isEmpty()) {
			return Collections.emptyList();
		}
		List<PropertySource<?>> propertySources = new ArrayList<>(properties.size());
		for (int i = 0; i < properties.size(); i++) {
			String documentNumber = (properties.size() != 1) ? " (document #" + i + ")" : "";
			propertySources.add(new OriginTrackedMapPropertySource(name + documentNumber,
					Collections.unmodifiableMap(properties.get(i)), true));
		}
		return propertySources;
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private List<Map<String, ?>> loadProperties(Resource resource) throws IOException {
		String filename = resource.getFilename();
		List<Map<String, ?>> result = new ArrayList<>();
		if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
			result.add((Map) PropertiesLoaderUtils.loadProperties(resource));
		}
		else {
			List<Document> documents = new MyOriginTrackedPropertiesLoader(resource).load();
			documents.forEach((document) -> result.add(document.asMap()));
		}
		return result;
	}
}

3.创建spring.factories文件

在resources资源目录下创建/META-INF/spring.factories文件

在这里插入图片描述

文件内容为


org.springframework.boot.env.PropertySourceLoader=\
com.xxx.config.MyPropertiesPropertySourceLoader

测试

创建application.properties文件


abc=中文测试

创建service类,使用@Value注入abc变量


@Value("${abc}")
private String abc;

分别在com.xxx.config.MyPropertiesPropertySourceLoader类、org.springframework.boot.env.PropertiesPropertySourceLoader类、org.springframework.boot.env.YamlPropertySourceLoader类的load方法打断点

以debug方式运行项目,可以看到只加载了com.xxx.config.MyPropertiesPropertySourceLoader类和org.springframework.boot.env.YamlPropertySourceLoader类,

发请求查看abc变量的值为:中文测试,已经不乱码了

最后

配置中心properties文件的中文属性也没有了乱码

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: 解决Springboot-application.properties中文乱码问题

本文链接: https://www.lsjlt.com/news/158673.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 解决Springboot-application.properties中文乱码问题
    目录Springboot-application.properties中文乱码设置application.properties为utf-8读取配置的中文结果打印分析Springboo...
    99+
    2022-11-12
  • 如何解决Springboot-application.properties中文乱码问题
    本篇内容主要讲解“如何解决Springboot-application.properties中文乱码问题”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何解决Springboot-applica...
    99+
    2023-06-21
  • 解决springboot application.properties server.port配置问题
    目录springboot application.properties server.port配置的问题下面就其中一个小问题做个记录内嵌tomcat的jar包依赖包含在pom中Spr...
    99+
    2022-11-12
  • python json.dumps中文乱码问题解决
    json.dumps(var,ensure_ascii=False)并不能完全解决中文乱码的问题 json.dumps在不同版本的Python下会有不同的表现, 注意下面提到的中文乱...
    99+
    2022-11-12
  • python中文编码乱码问题的解决
    目录前言:一、什么是字符编码。1.ASCII2.GB23123.Unicode4.UTF-8二、Python2中的字符编码三、decode()与encode()方法四、一个字符编码的...
    99+
    2022-11-12
  • PHP怎么解决中文乱码问题
    这篇文章主要介绍“PHP怎么解决中文乱码问题”,在日常操作中,相信很多人在PHP怎么解决中文乱码问题问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”PHP怎么解决中文乱码问题”的疑惑有所帮助!接下来,请跟着小编...
    99+
    2023-06-17
  • php.ini如何解决中文乱码问题
    本篇内容主要讲解“php.ini如何解决中文乱码问题”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“php.ini如何解决中文乱码问题”吧!php.ini解决中文乱码的方法:首先打开php.ini...
    99+
    2023-06-20
  • MySQL中文乱码问题解决方案
    linux 中 MySQL 出现中文乱码问题如下操作 编辑vi /etc/my.cnf 文件,添加图中标记三行 [client] default-character-set=utf8 [mysqld] chara...
    99+
    2022-05-17
    MySQL 中文乱码
  • ajax中文乱码问题怎么解决
    本篇内容主要讲解“ajax中文乱码问题怎么解决”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“ajax中文乱码问题怎么解决”吧! a...
    99+
    2022-10-19
  • 如何解决AJAX中文乱码问题
    本篇内容介绍了“如何解决AJAX中文乱码问题”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成! ...
    99+
    2022-10-19
  • 如何解决ubuntu16.04中文乱码问题
    解决ubuntu16.04中文乱码的方法:1、在ubuntu终端命令行中使用“apt-get install language-pack-zh-hans”命令安装好中文语言包;2、在bash.bashrc配置文件中写入“export LC_...
    99+
    2022-10-19
  • 解决IDEA的Terminal中文乱码问题
    当我提交项目输入中文描述信息的时候,发现IDEA 的 Terminal无法显示中文信息,显示的是下面这样的 因为我的终端设置了git.bash窗口,所以我以为是git乱码问题,我打...
    99+
    2022-11-12
  • 解决Git Bash中文乱码的问题
    方法一 一、桌面右击,点击“Git Bash Here” 二、在弹出的黑窗口,右击,选择“options” 三、在弹出的窗口,选择...
    99+
    2022-11-13
  • php如何解决中文乱码问题
    小编给大家分享一下php如何解决中文乱码问题,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!php解决中文乱码的方法:1、在head标签里面加入UTF8编码;2、在...
    99+
    2023-06-07
  • 怎么解决Suse中文乱码问题
    怎么解决Suse中文乱码问题,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。随着我们学习Suse linux的深入,我们也面临着很多问题,今天所要讲的是Suse中文乱码问题,Su...
    99+
    2023-06-17
  • jsp中文乱码问题怎么解决
    这篇文章主要介绍“jsp中文乱码问题怎么解决”,在日常操作中,相信很多人在jsp中文乱码问题怎么解决问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”jsp中文乱码问题怎么解决”的疑惑有所帮助!接下来,请跟着小编...
    99+
    2023-06-30
  • mysql5.5中文乱码问题如何解决
    本篇内容介绍了“mysql5.5中文乱码问题如何解决”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!查看MySQL的字符集show ...
    99+
    2023-06-30
  • MYSQL中文乱码问题如何解决
    这篇文章主要介绍了MYSQL中文乱码问题如何解决的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇MYSQL中文乱码问题如何解决文章都会有所收获,下面我们一起来看看吧。一、乱码的原因: client客户端的编码不是...
    99+
    2023-07-02
  • 怎么解决FireFTP中文乱码问题
    怎么解决FireFTP中文乱码问题,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。FireFTP是一个Firefox浏览器插件,用Firefox浏览器的人肯定知道,但是在用的时候...
    99+
    2023-06-16
  • python如何解决中文编码乱码问题
    小编给大家分享一下python如何解决中文编码乱码问题,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!一、什么是字符编码。要彻底解决字符编码的问题就不能不去了解到底...
    99+
    2023-06-25
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作