SpringBoot读取application.properties中⽂乱码的解决办法1.问题描述
由于业务需求需要在application.properties中配置⼀个带有中⽂字符串的参数,注⼊到业务类中,但是发现注⼊的中⽂是乱码的。⼤概情况如下所⽰:
@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class UnitTest {
@Value("${name}")
private String name;
@Test
public void test1() throws UnsupportedEncodingException {
System.out.println("中⽂内容:" + name);
}
python lambda用法}
打印输出结果:
2.问题解决
2.1⽹络上已有的解决办法
看到这个问题,第⼀时间去⽹上博客搜索。⽹络上的解决办法基本⼀致,概括为以下三种。
2.1.1修改IDEA编码
在IDEA中将所有的编码设置为UTF-8同时勾上⼀个叫Transparent native-to-ascii conversion的选项,然后重新创建
application.properties的⽂件
运⾏结果:
的。。。所以此⽅式我不做推荐。
就是将application.properties的⽂件修改为l的结构,重启项⽬。
运⾏效果
证明是可⾏的。这种⽅式可以根据⾃⼰需求选择,但是当配置⽂件的内容层级较深时也不推荐,容易看错⾏配置。
2.1.3在读取properties⽂件的时候设置编码
@Configuration
@PropertySource(value = "classpath:application.properties", encoding = "utf-8")
public class MyConfig {
@Value("${name}")
private String name;
@PostConstruct
public void init() {
System.out.println("name is :" + name);
}森系小清新ppt模板
}
亲测发现这种⽅式针对application.properties是不⾏的。
但是针对其他名称的properties⽂件是可以的
@Configuration
亚洲7号加密节目@PropertySource(value = "classpath:test.properties", encoding = "utf-8")
public class MyConfig2 {
@Value("${name2}")
private String name;
@PostConstruct
public void init() {
System.out.println("name2 is :" + name);
}
}
运⾏结果
2.2编码层⾯解决办法(个⼈研究的)
2.2.1研究过程(不喜欢的直接看2.2.2解决办法)
以上⽹络上的解决办法,都不太适合个⼈的话,请留意这⼀种终极解决办法,本⼈研究得出的,如有问题望各位⼤佬评论指证。通过阅读源码发现在ConfigFileApplicationListener中有如下代码
private PropertySource<?> doLoadIntoGroup(String identifier, String location,
Profile profile) throws IOException {
Resource resource = Resource(location);
properties文件用什么打开PropertySource<?> propertySource = null;
StringBuilder msg = new StringBuilder();
if (resource != null && ists()) {
instanced
String name = "applicationConfig: [" + location + "]";
String group = "applicationConfig: [" + identifier + "]";
/
/重点就在这⾥,可以在这⾥打个断点,发现在这⾥就已经把application.properties的内容读取到了    propertySource = this.propertiesLoader.load(resource, group, name,
(profile == null ? null : Name()));
...
accepted短语}
好了,那么进⼊这个⽅法内部看
进⼊PropertiesPropertySourceLoader查看load⽅法