在 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"));
}
測試結果: