Sping boot 之 @Value("${xxx}") 注解获取配置文件内容

1、注解方式读取
1-1、@PropertySource配置文件路径设置,在类上添加注解,如果在默认路径下可以不添加该注解
需要用@PropertySource的有:
  • 例如非application.properties 主配置文件
  • 例如有多配置文件引用,若取两个配置文件中有相同属性名的值,则取值为最后一个配置文件中的值
    •    @PropertySource({"classpath:my/my1.properties","classpath:my/my2.properties"}) public class TestController
  • 在application.properties中的文件,直接使用@Value读取即可,applicarion的读取优先级最高
     
 
2-2、@Value属性名,在属性名上添加该注解
@Value("${my.name}")
private String myName;
示例1:使用@Value读取application.properties里的配置内容
配置文件application.properties
spring.application.name=tn
 
测试类:
@RestController
//@PropertySource("classpath:my.properties") //application.properties不需要配置注解 默认读取
public class TaskController {
 
@Value("${my.name}")
private String userName;
 
@RequestMapping(value ="/")
public String testDemo() {
     System.out.println("userName:" + userName);
     return "hello word!";
   }
 
}
结果:
userName: tn
 
 
示例2:使用@Value读取my.properties里的配置内容
配置文件my.properties
name=tn
 
测试类:
@RestController
@PropertySource("classpath:my.properties")
public class TaskController {
 
@Value("${my.name}")
private String userName;
 
@RequestMapping(value ="/")
public String testDemo() {
     System.out.println("userName:" + userName);
     return "hello word!";
   }
 
}
结果:
        userName: tn
 
 
示例3:static静态变量使用@Value注入方式
错误写法:Config.getEnv()会返回null
@Component
@PropertySource({ "classpath:my.properties" })
public class MyConfig {
  @Value("${name}")
   private static String name;
 
  public static String getName() {
     return name;
   }
 
    public static void setName(String name) {
    MyConfig.name= name;
    }
}
正确写法:在非静态方法setEnv前使用@Value注解
@Component
@PropertySource({ "classpath:my.properties" })
public class MyConfig {
 
   private static String name;
 
  public static String getName() {
    return name;
   }
  @Value("${name}")
   public void setName(String name) {
     MyConfig.name= name;
  }
}
 
 

猜你喜欢

转载自www.cnblogs.com/tanning/p/9719027.html
今日推荐