我是靠谱客的博主 虚幻蜻蜓,这篇文章主要介绍使SpringBoot配置文件application.properties支持中文版本说明为什么不支持中文重写读取application.properties文件的逻辑测试最后,现在分享给大家,希望可以做个参考。

目录

  • 版本说明
  • 为什么不支持中文
    • 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编码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
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} -&gt; * {@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", "trnf" }; 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.创建PropertiesPropertySourceLoader文件

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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.创建spring.factories文件

在resources资源目录下创建/META-INF/spring.factories文件
在这里插入图片描述
文件内容为

复制代码
1
2
3
org.springframework.boot.env.PropertySourceLoader= com.xxx.config.MyPropertiesPropertySourceLoader

测试

  1. 创建application.properties文件
复制代码
1
2
abc=中文测试
  1. 创建service类,使用@Value注入abc变量
复制代码
1
2
3
@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支持中文版本说明为什么不支持中文重写读取application.properties文件的逻辑测试最后的全部内容,更多相关使SpringBoot配置文件application.properties支持中文版本说明为什么不支持中文重写读取application.properties文件内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部