SpringBoot之通過yaml繫結注入資料
阿新 • • 發佈:2019-01-07
依賴包:
<!--配置檔案註解提示包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
JavaBean:(此處使用lombok,可省略setter、getter等方法)
1 package org.springboot.model; 2 3 import lombok.Data; 4 import org.springframework.beans.factory.annotation.Value; 5 import org.springframework.boot.context.properties.ConfigurationProperties; 6 import org.springframework.stereotype.Component;7 8 import java.util.Date; 9 import java.util.Map; 10 11 /** 12 * @Auther:GongXingRui 13 * @Date:2019/1/7 14 * @Description: 通過yaml繫結,注入資料的模型 15 **/ 16 17 @Data 18 @Component 19 @ConfigurationProperties(prefix = "teather") 20 public class Teather { 21 @Value("小紅") //單個賦值,優先順序低 22 private String name;23 private String age; 24 private Date birthday; 25 private Boolean gender; 26 private String[] hobbies; //集合處理方式和陣列相同 27 // {省:江蘇,市:南京} 28 private Map<String, Object> location; 29 30 }
application.yml
# 通過yaml繫結,注入資料 teather: name: Cate age: 29 birthday: 1989/01/16 gender: true hobbies: [唱歌,跳舞] location: {Province: "江蘇",City: "南京"}
已縮排來區分同級,並且冒號後必須有空格。
測試程式碼:
package org.springboot; import org.junit.Test; import org.junit.runner.RunWith; import org.springboot.model.Teather; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DemoApplicationTests { @Autowired Teather teather; //通過yaml繫結,注入資料 @Test public void testTeather() { System.out.println(teather); } }
執行結果
Teather(name=Cate, age=29, birthday=Mon Jan 16 00:00:00 CST 1989, gender=true, hobbies=[唱歌, 跳舞], location={Province=江蘇, City=南京})
此處繫結注入型別分為批量注入和單個注入,批量注入的優先順序較高,兩種方式的比較如下圖: