今天玩SpringBoot时碰到了小坑,就是在获取yml自定义配置时的乱码问题。
在查询相关问题时,大部分解决办法都是说配置Idea的配置文件编码格式。如下:
而我配置之后也不见效果,折腾好一会儿后才知道了真相。
这里测试了两种方式:
单独从yml配置文件中获取配置信息方式:
创建了一个yml文件,其内容如下:
获取配置类如下:
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
50package com.minant.mant.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; /** * @ClassName MyWebConfig * @Description TODO 我的个人配置 * @Author MinAnt * @Date 2020/11/15 * @Version V1.0 */ @Component @PropertySource(value = "classpath:myweb.yml", encoding = "utf-8") @ConfigurationProperties(prefix = "myweb") public class MyWebConfig { @Value("${name}") private String name; @Value("${age}") private Integer age; @Value("${sex}") private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
这种方式获取配置信息时要注意,除了配置Idea的文件编码格式外,还需要注意配置读取的编码格式,即:@PropertySource(value = "classpath:myweb.yml", encoding = "utf-8")这个注解的encoding 属性要加上,配置文件中的中文不需要加引号就可以,加引号会把引号也带出来。
再一种就是通过spring.profiles.include的配置方式配置的自定义属性文件:
在application.yml中加上如下配置:
其中命名是有规范的,如下:
其中application-mypro.yml和application-resource.yml都是我的自定义配置文件,就那mypro.yml测试,其内容:
这种方式的中文加不加引号都可以,加了引号也会忽略掉不会带出来。
配置类如下:
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
49package com.minant.mant.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; /** * @ClassName MyWebConfig * @Description TODO 我的个人配置 * @Author MinAnt * @Date 2020/11/15 * @Version V1.0 */ @Component @ConfigurationProperties(prefix = "myweb") public class MyWebConfig { private String name; private Integer age; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
以上两种都是以配置了Idea文件编码格式为前提(也就是最前面的那个Setting配置),至于用哪种方式,跟据个人喜好吧。
最后,如果是这些都不行,那么就重新创建配置文件,再重启下Idea吧,Idea的缓存是有点坑人的,总会导致一些奇奇怪怪的问题。。。。
最后
以上就是标致鸭子最近收集整理的关于记SpringBoot获取yml自定义配置时中文乱码的小坑的全部内容,更多相关记SpringBoot获取yml自定义配置时中文乱码内容请搜索靠谱客的其他文章。
发表评论 取消回复