解决@Value("${name}")获取application.properties中定义的参数中文乱码的问题

xiaoxiao2025-10-10  19

 

application.properties中参数如图:

pom.xml中设置如图

 

但代码

import org.springframework.web.bind.annotation.RestController; @RequestMapping("/hello") @RestController public class HelloController { @Value("${author.name}") private String name ; @Value("${author.sex}") private String sex; @Value("${author.birthday}") private String birthday; @RequestMapping("/index") public String index(){ String str = "你好笨笔!"+"name:"+name+";sex:"+sex+";birthday:"+birthday; System.out.println(str); return str; } }

输出的结果却是:

你好笨笔!name:"��˧��motto";sex:"��";birthday:"2018-12-24"

 

将application.properties复制到桌面查看它的编码:

为了验证一下,将pom.xml的编码配置改为GB2312,结果却是

浣�濂界�ㄧ��!name:"´ó˧¸çmotto";sex:"ÄÐ";birthday:"2018-12-24"

得出的结果不但原来的没好,原来好的也变不好了。

说明我们大环境中的编码是UTF-8的。那么把application.properties的编码格式改为UTF-8再放到工程中

 

重新运行得到的结果是

你好笨笔!name:"大å¸å¥motto";sex:"ç·";birthday:"2018-12-24"

 

和首次一样。然后查询百度,说需要改setting中的File Encodings。于是进去修改

,修改后还是没解决。

其实,application.properties是不应该写中文的,得用经过UTF-8的字符代替

 

得到结果为

你好笨笔!name:"大帅哥motto";sex:"男";birthday:"2018-12-24"

 

 

 

 

 

转载请注明原文地址: https://www.6miu.com/read-5037668.html

最新回复(0)