spring boot使用@Value,@PropertySource注解使用 spring boot使用@Value,@PropertySource注解使用

spring boot使用@Value,@PropertySource注解使用

在spring boot中,有些变量根据需求配置在application.properties中,

在应用程序中使用@Value注解获取值。

eg:

在配置application.properteis配置一个键值对:

TestValue=This is my test!

程序中获取方式:

[java]  view plain  copy
  1. /** 使用@value注解,从配置文件读取值 */  
  2.   
  3. @Value("${TestValue}")  
  4. 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
  1. package com.lanhuigu.hello;  
  2.   
  3. import org.springframework.beans.factory.annotation.Value;  
  4. import org.springframework.context.annotation.PropertySource;  
  5. import org.springframework.web.bind.annotation.RequestMapping;  
  6. import org.springframework.web.bind.annotation.ResponseBody;  
  7. import org.springframework.web.bind.annotation.RestController;  
  8. /** 
  9.  * @RestController这个注解等价于spring mvc用法中的@Controller+@ResponseBody  
  10.  */  
  11. @RestController  
  12. @PropertySource(value = {"classpath:application.properties"},encoding="utf-8")  
  13. @RequestMapping(value="hello")  
  14. public class HelloController {  
  15.     /** 使用@value注解,从配置文件读取值 */  
  16.     @Value("${TestValue}")  
  17.     private String testValueAnno;  
  18.       
  19.     @RequestMapping(value="sayHello")  
  20.     @ResponseBody  
  21.     private String sayHello() {  
  22.         System.out.println("测试:"+testValueAnno+"一意孤行!");  
  23.         return "hello world!";  
  24.     }  
  25. }  
通过以上方式,能够解决spring boot通过@Value读取变量值出现中文乱码问题。

猜你喜欢

转载自blog.csdn.net/inthat/article/details/80501069
今日推荐