|
SpringBoot配置文件詳解[云圖智聯]1
發表時間:2020-07-02 11:52 免費學習視頻歡迎關注云圖智聯: 配置文件詳解 application.properties properties配置文件我們之前都有接觸,今天就讓我們來認識一下yaml配置文件吧。
YAML是"YAML Ain't a Markup Language"(YAML不是一種標記語言)的遞歸縮寫。在開發的這種語言時,YAML 的意思其實是:"Yet Another Markup Language"(仍是一種標記語言),但為了強調這種語言以數據做為中心,而不是以標記語言為重點,而用反向縮略語重命名。 YAML基本語法
port: 8081 path: /example 字面量:普通的值(整數、浮點數、字符串、布爾、Null值、時間、日期) key: value(字面值直接寫上就可以)
boolean: TRUE #true,True都可以 float: - 3.14 - 6.8523015e+5 #可以使用科學計數法 int: - 123 - 0b1010\_0111\_0100\_1010\_1110 #二進制表示 null: nodeName: 'node' parent: ~ #使用~表示null string: - 哈哈 - 'Hello world' #可以使用雙引號或者單引號包裹特殊字符 - newline newline2 #字符串可以拆成多行,每一行會被轉化成一個空格 date: - 2018-02-17 #日期必須使用ISO 8601格式,即yyyy-MM-dd user: username: root password: rootpwd user:{username: root,password: rootpwd} 示例: pets: - cat - dog pets: \[cat,dog\] 注釋 文本塊 value: | hello world! +表示保留文字塊末尾的換行,-表示刪除字符串末尾的換行。 value: | hello value: |\- hello value: |+ hello \# 輸出:hello\\n hello hello\\n\\n(有多少個回車就有多少個\\n) >:使用 > 標注的文本內容縮進表示的塊,將塊中回車替換為空格,最終連接成一行 value: > hello world! \# 輸出:hello 空格 world! \## 測試ConfigurationProperties user: userName: root isAdmin: true regTime: 2020/01/01 isOnline: 1 maps: {k1 : v1,k2: v2} lists: - list1 - list2 address: tel: 15899988899 name: 上海市 2.1 User類 import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component;
public String toString() { public String getUserName() { public void setUserName(String userName) { public boolean isAdmin() { public void setAdmin(boolean admin) { public Date getRegTime() { public void setRegTime(Date regTime) { public Long getIsOnline() { public void setIsOnline(Long isOnline) { public Map<String, Object> getMaps() { public void setMaps(Map<String, Object> maps) { public List<Object> getLists() { public Address getAddress() { } 需要將配置文件中每個屬性都映射到這個組件,注意:記得加@Component注解,這樣才能將這個組件加載到Spring容器中 @ConfigurationProperties(prefix = "user") 通過prefix屬性配置的user在配置文件中綁定user對象,將配置文件中的屬性值直接映射到bean屬性中 2.2 Address類 public class Address { private String tel; private String name; @Override public String toString() { return "Address{" + "tel='" + tel + '\'' + ", name='" + name + '\'' + '}'; } public String getTel() { return tel; } public void setTel(String tel) { this.tel= tel; } public String getName() { return name; } public void setName(String name) { this.name= name; } } ok,這時候啟動項目的時候就可在容器中直接使用user對象了,現在我們使用spirng自帶的測試類,測試一下 import com.example.easy.entity.Stu; @Autowired System.out.println(user); } } 說明: 運行效果 免費學習視頻歡迎關注云圖智聯: |