Spring Boot获取配置文件application.yml的属性值

在 Spring Boot 项目中,配置文件格式有两种,一个是 properties ,另一个是 yml 。虽然 properties 文件比较常见,但是相对于 properties 而言,yml 文件的配置项更加简洁明了,可读性很强,不仅如此,yml 文件还有另外一个重要的特点,就是 yml 中的数据是有序的,properties文件中的数据是无序的。我们都知道SpringBoot工程默认的配置文件application.properties 中配置的属性用@Value注解注入可以取到值,但是application.yml中配置的属性用@Value注解注入后取值是null,那么能否把application.yml文件中的属性值用@Value注解或者其他方式取到值了,办法是有的,笔者给大家分享一种方式对application.yml文件通过注解取值。

注入方式:类型安全的属性注入

首先定义application.yml文件,配置下面几个属性

student:
  name: 张三
  age: 22
  score:
    shuxue: 89
    yingyu: 67
    yuwen: 83

 接着通过注解注入这些属性值

@Component
@ConfigurationProperties(prefix="student",ignoreInvalidFields=true, ignoreUnknownFields=true)
public class Student {

   private String name;
   private Integer age;
   private Map<String,Integer> score  = new HashMap<String,Integer>();
}

注意:@Component注解表示申明为一个被Spring 容器管理的组件,此处为了演示get,set方法省略了,开发者自行加上就行。

Spring Boot 引入了类型安全的属性注入方式,主要是引入 @ConfigurationProperties(prefix = "") 注解,并且配置了属性的前缀,此时会自动将 Spring 容器中对应的数据注入到对象对应的属性中,就不用通过@Value()方式注入了,省时又省力。

注入测试

  @Autowired
  private Student student;

  @GetMapping(value="/ceshi")
  @ResponseBody
  private  void printInfo() throws JsonProcessingException{
    System.out.println("学生姓名:"+student.getName());
    System.out.println("学生年龄:"+student.getAge());
    System.out.println("全部成绩:"+student.getScore());
    System.out.println("数学成绩:"+student.getScore().get("shuxue"));
    System.out.println("英语成绩:"+student.getScore().get("yingyu"));
    System.out.println("语文成绩:"+student.getScore().get("yuwen"));
}

测试结果:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章