解決Springboot-application.properties中文亂碼問題
Springboot-application.properties中文亂碼
Springboot-application.properties編碼問題 設(shè)置application.properties為utf-8讀取配置的中文結(jié)果打印分析
設(shè)置application.properties為utf-8
UTF-8,這樣在windows和linux服務(wù)器中查看配置文件都能正常顯示中文。否則可能中文無法正常顯示。

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;
}
}
結(jié)果打印
需要將數(shù)據(jù)編碼從iso8859-1轉(zhuǎn)為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文件被設(shè)置為哪種編碼格式,最終還是以ISO-8859-1的編碼格式進(jìn)行加載。
而yml/yaml默認(rèn)以UTF-8加載
Springboot配置文件application.properties支持中文
版本說明
本文不完全基于springboot-2.4.5,各版本需要重寫類的邏輯各有不同,本文的代碼只可模仿,不可復(fù)制
為什么不支持中文
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下有兩個默認(rèn)實現(xiàn)

org.springframework.boot.env.YamlPropertySourceLoader負(fù)責(zé)讀取yml文件,
org.springframework.boot.env.PropertiesPropertySourceLoader負(fù)責(zé)讀取properties和xml文件

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

以ISO_8859_1編碼方式讀取properties文件
重寫讀取application.properties文件的邏輯
使SpringBoot配置文件application.properties支持中文
1.創(chuàng)建OriginTrackedPropertiesLoader文件
復(fù)制org.springframework.boot.env.OriginTrackedPropertiesLoader文件內(nèi)容,并修改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;
/**
* Class to load {@code .properties} files into a map of {@code String} ->
* {@link OriginTrackedValue}. Also supports expansion of {@code name[]=a,b,c} list style
* values.
*
* @author Madhura Bhave
* @author Phillip Webb
* @author Thiago Hirata
*/
public class MyOriginTrackedPropertiesLoader {
private final Resource resource;
/**
* Create a new {@link OriginTrackedPropertiesLoader} instance.
* @param resource the resource of the {@code .properties} data
*/
MyOriginTrackedPropertiesLoader(Resource resource) {
Assert.notNull(resource, "Resource must not be null");
this.resource = resource;
}
/**
* Load {@code .properties} data and return a list of documents.
* @return the loaded properties
* @throws IOException on read error
*/
List<Document> load() throws IOException {
return load(true);
}
/**
* Load {@code .properties} data and return a map of {@code String} ->
* {@link OriginTrackedValue}.
* @param expandLists if list {@code name[]=a,b,c} shortcuts should be expanded
* @return the loaded properties
* @throws IOException on read error
*/
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();
}
/**
* Reads characters from the source resource, taking care of skipping comments,
* handling multi-line values and tracking {@code '\'} escapes.
*/
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 == '-';
}
}
/**
* A single document within the properties file.
*/
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.創(chuàng)建PropertiesPropertySourceLoader文件
復(fù)制org.springframework.boot.env.PropertiesPropertySourceLoader文件內(nèi)容,并將調(diào)用org.springframework.boot.env.OriginTrackedPropertiesLoader類改為調(diào)用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;
/**
* Strategy to load '.properties' files into a {@link PropertySource}.
*
* @author Dave Syer
* @author Phillip Webb
* @author Madhura Bhave
* @since 1.0.0
*/
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.創(chuàng)建spring.factories文件
在resources資源目錄下創(chuàng)建/META-INF/spring.factories文件

文件內(nèi)容為
org.springframework.boot.env.PropertySourceLoader=\ com.xxx.config.MyPropertiesPropertySourceLoader
測試
創(chuàng)建application.properties文件
abc=中文測試
創(chuàng)建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類,
發(fā)請求查看abc變量的值為:中文測試,已經(jīng)不亂碼了
最后
配置中心properties文件的中文屬性也沒有了亂碼
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
通過實例學(xué)習(xí)Spring @Required注釋原理
這篇文章主要介紹了通過實例學(xué)習(xí)Spring @Required注釋原理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03
Java進(jìn)階學(xué)習(xí):網(wǎng)絡(luò)服務(wù)器編程
Java進(jìn)階學(xué)習(xí):網(wǎng)絡(luò)服務(wù)器編程...2006-12-12
Java?Lambda表達(dá)式常用的函數(shù)式接口
這篇文章主要介紹了Java?Lambda表達(dá)式常用的函數(shù)式接口,文章基于Java?Lambda表達(dá)式展開對常用的函數(shù)式接口的介紹,具有一的的參考價值需要的小伙伴可以參考一下2022-04-04
Java 超詳細(xì)圖解集合框架的數(shù)據(jù)結(jié)構(gòu)
什么是集合框架呢?集合框架是為表示和操作集合而規(guī)定的一種統(tǒng)一的標(biāo)準(zhǔn)的體系結(jié)構(gòu)。最簡單的集合如數(shù)組、列表和隊列等,任何集合框架一般包含:對外的接口、接口的實現(xiàn)和對集合運算的算法2022-04-04

