spring boot使用@Value,@PropertySource注解使用
******@Value******
在spring boot中,有些变量根据需求配置在application.properties中,
在应用程序中使用@Value注解获取值。
eg:
在配置application.properteis配置一个键值对:
TestValue=This is my test!
程序中获取方式:
[java] view plain copy
- /** 使用@value注解,从配置文件读取值 */
- @Value("${TestValue}")
- private String testValueAnno;
将变量testValueAnno值初始化为This is my test!
******@PropertySource******
@PropertySource注解用于指定目录,指定编码读取properties文件,
如果将TestValue在配置文件中对应的值加上中文,通过@Value读取
到的值会出现中文乱码,因为spring boot加载application.properties
采用的是unicode编码形式,后台读取的变量值自然是乱码,解决办法
就是通过@PropertySource注解指定文件路径,通过utf-8的编码读取文件。
eg:
[java] view plain copy
- package com.lanhuigu.hello;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.PropertySource;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.bind.annotation.RestController;
- /**
- * @RestController这个注解等价于spring mvc用法中的@Controller+@ResponseBody
- */
- @RestController
- @PropertySource(value = {"classpath:application.properties"},encoding="utf-8")
- @RequestMapping(value="hello")
- public class HelloController {
- /** 使用@value注解,从配置文件读取值 */
- @Value("${TestValue}")
- private String testValueAnno;
- @RequestMapping(value="sayHello")
- @ResponseBody
- private String sayHello() {
- System.out.println("测试:"+testValueAnno+"一意孤行!");
- return "hello world!";
- }
- }
通过以上方式,能够解决spring boot通过@Value读取变量值出现中文乱码问题。