SpringBoot專欄:配置檔案注入知識點彙總(第二講)
阿新 • • 發佈:2018-12-23
配置檔案注入案例講解(知識點彙總)
配置檔案佔位符
${random.value}、${random.int}、${random.long} ${random.int(10)}、${random.int[1024,65536]}
屬性配置佔位符
– 可以在配置檔案中引用前面配置過的屬性(優先順序前面配置過的這裡都能用)。
– ${app.name:預設值}來指定找不到屬性時的預設值
配置檔案載入位置
spring boot 啟動會掃描以下位置的application.properties或者 application.yml檔案作為Spring boot的預設配置檔案
– file:./config/
– file:./ – classpath:/config/
– classpath:/
– 以上是按照優先順序從高到低的順序,所有位置的檔案都會被載入,高優先順序配置內容會覆蓋低優先順序配置內容。 – 我們也可以通過配置spring.config.location來改變預設配置
Spring Configuration 和 Component 區別(精簡彙總版)
參考:https://www.toutiao.com/i6636541118316020231/
配置檔案值注入(各種型別list、map、int、Sting、boolen等)
建立實體類:Student
@Component @ConfigurationProperties(prefix = "student") public class Student { private String lastName; private Integer age; private Boolean boss; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Book book; /** * 特別注意!!特別注意!!:如果通過字首的方式注入,一定要有get set 方法 * @return */ @Override public String toString() { return "Student{" + "lastName='" + lastName + '\'' + ", age=" + age + ", boss=" + boss + ", birth=" + birth + ", maps=" + maps + ", lists=" + lists + ", book=" + book + '}'; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Boolean getBoss() { return boss; } public void setBoss(Boolean boss) { this.boss = boss; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public Map<String, Object> getMaps() { return maps; } public void setMaps(Map<String, Object> maps) { this.maps = maps; } public List<Object> getLists() { return lists; } public void setLists(List<Object> lists) { this.lists = lists; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } }
application.properties配置相關屬性
student.last-name=你好spring cloud ${random.uuid}
student.age=${random.int}
student.birth=2017/12/15
student.boss=false
student.maps.k1=mapv1
student.maps.k2=mapv2
student.lists=spring boot ,spring cloud ,spring mvc
student.book.name=${student.hello:hello}_book
student.book.price=15
執行測試類
我們可以看到Student已經被注入相關值
同樣Teacher類也可以通過@PropertySource(value = {"classpath:teacher.properties"})的方式注入
原始碼下載地址:
https://github.com/shinians/springboot-demos
專案springboot-02-config-simple
希望對您有所幫助。