使用@Value读取application.properties
代码演示: 在appliaction.properties中写入需要的配置信息
server.servlet.context-path=/myboot
server.port=8085
name=小芳
创建一个@Controller
@Controller
public class HelloController {
@Value("${name}")
private String name;
@RequestMapping(value = "/doSome",produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String doSome(){
return name;
}
}
网页输出结果:出现中文乱码  可以看到@RequestMapping(value = “/doSome”,produces = {“application/json;charset=UTF-8”})是设置了UTF-8证明不是输出的时候乱码了,而是读取的时候乱码,查阅了一下资料发现@Value读取properties文件的时候不是用UFT-8读取所以就需要去配置一下Springboot,然后找到三个方法
1.在properties文件中加入这几行信息
spring.banner.charset=UTF-8
spring.messages.encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.force=true
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8
然后设置 File Encodings的Transparent native-to-ascii conversion为true  此时重启springboot可以显示中文 
2.加入注解
在Controller类的这个位置加上 @PropertySource(value = “classpath:application.properties”,encoding = “UTF-8”) 
3.使用.yml就不需要配置这些啦
server:
servlet:
context-path: /myboot
port: 8085
name: "酷酷"
 希望对大家有帮助
|