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

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

******@Value******

在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读取变量值出现中文乱码问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值