目录

  • 版本说明
  • 为什么不支持中文
    • PropertySourceLoader接口
    • PropertiesPropertySourceLoader类
    • OriginTrackedPropertiesLoader类
  • 重写读取application.properties文件的逻辑
    • 1.创建OriginTrackedPropertiesLoader文件
    • 2.创建PropertiesPropertySourceLoader文件
    • 3.创建spring.factories文件
  • 测试
  • 最后

版本说明

本文不完全基于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;/*** 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));}@Overridepublic 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.创建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;/*** 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";@Overridepublic String[] getFileExtensions() {return new String[] { "properties", "xml" };}@Overridepublic 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

测试

  1. 创建application.properties文件
abc=中文测试
  1. 创建service类,使用@Value注入abc变量
@Value("${abc}")
private String abc;
  1. 分别在com.xxx.config.MyPropertiesPropertySourceLoader类、org.springframework.boot.env.PropertiesPropertySourceLoader类、org.springframework.boot.env.YamlPropertySourceLoader类的load方法打断点
  2. 以debug方式运行项目,可以看到只加载了com.xxx.config.MyPropertiesPropertySourceLoader类和org.springframework.boot.env.YamlPropertySourceLoader类,
  3. 发请求查看abc变量的值为:中文测试,已经不乱码了

最后

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

使SpringBoot配置文件application.properties支持中文相关推荐

  1. springboot配置文件application.properties参阅文章

    date: 2018/11/12 10:25:51 application.properties配置文件 仅供查阅 #########COMMON SPRING BOOT PROPERTIES#### ...

  2. SpringBoot 配置文件 application.properties(二)

    mvc spring.mvc.async.request-timeout 设定async请求的超时时间,以毫秒为单位,如果没有设置的话,以具体实现的超时时间为准,比如tomcat的servlet3的话 ...

  3. java配置文件变量替换_SpringBoot 配置文件application.properties配置参数替换或者注入的几种方式...

    想要忽略properties中的某些属性,引发的对SpringBoot中的application.properties外部注入覆盖,以及properties文件使用的思考. SpringBoot 配置 ...

  4. 【SpringBoot零基础案例03】【IEDA 2021.1】SpringBoot框架核心配置文件application.properties的使用

    新建模块,并在src-main-java下新建IndexController类 package com.zx.springboot.springbootcontextpath.controller;i ...

  5. springboot中配置文件application.properties的配置详情,数据源配置

    pring Boot使用了一个全局的配置文件application.properties,放在src/main/resources目录下或者类路径的/config下.Sping Boot的全局配置文件 ...

  6. dubbo提供者主配置文件application.properties

    1.用户中心提供者主配置文件application.properties内容如下 ## 与当前应用相关配置 # 应用名称 spring.application.name=power-dubbo-pro ...

  7. SpringBoot中整合freemarker时配置文件application.properties示例代码

    场景 整合过程参照: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/89074931 实现 如果要想配置freemarker的一些 ...

  8. 05全局配置文件application.properties详解

    Spring Boot 提供了大量的自动配置,极大地简化了spring 应用的开发过程,当用户创建了一个 Spring Boot 项目后,即使不进行任何配置,该项目也能顺利的运行起来.当然,用户也可以 ...

  9. 是时候搞清楚 Spring Boot 的配置文件 application.properties 了!

    在 Spring Boot 中,配置文件有两种不同的格式,一个是 properties ,另一个是 yaml . 虽然 properties 文件比较常见,但是相对于 properties 而言,ya ...

最新文章

  1. 《Framework Design Guidelines 2nd Edition》推荐
  2. golang中的strings.SplitN
  3. 夜貓子”必需的!——融合夜視技術
  4. vue 2个方法先后执行_有效快速制作工资条的2个方法
  5. 安全狗服云PC端V2.5.1发布 助力服务器安全运维
  6. 长三角协同优势产业基金正式设立,总规模1000亿
  7. FreeTextBox备忘
  8. 身份证前6位地区编码sql
  9. 微信公众号开发_调用新闻查询接口_回复图文消息
  10. 使用Eclipse编译运行MapReduce程序_Hadoop2.6.0_Ubuntu/CentOS
  11. 面试官:淘宝七天自动确认收货,可以怎么实现?
  12. uva 12307 - Smallest Enclosing Rectangle(旋转卡壳)
  13. (CCTV2视频)中国动画80年
  14. 数据治理的四字箴言:理、采、存、用
  15. OpenGL---实例 球体 画圆锥
  16. 攀藤 5003粉尘激光传感器arduino使用
  17. 单片机c语言交通灯源程序,基于80C51单片机的交通灯C语言源程序
  18. 锐捷认证客户端——多网卡限制破解
  19. python正则表达式01
  20. android横竖屏切换方法,Android横竖屏切换的生命周期

热门文章

  1. MySQL中, in和or 会走索引吗
  2. 郭金东金浦集团旗下钟山化工发明专利获得国家授权
  3. Ardunio、simulink分别控制继电器吸合的小程序
  4. 中小企业如何有效管理进销存?ERP系统有何作用?
  5. 企业工程项目管理系统源码-全面的工程项目管理
  6. TIDB数据库特性总结
  7. 试用平台常见的恶意买家退款情况以及处理方案分析
  8. 研大考研不是骗子,医学考研集训第一营
  9. 计算机修复画笔结果分析,《photoshop修复图像瑕疵》教学反思
  10. 休闲零食市场调查,哪些品类值得代理