你可能不知道的Spring Boot那點事
當前微服務的概念被炒的非常的火熱,而Spring Boot則被賦予了”為微服務而生“的稱號,相信看這篇文章的你,對微服務或者Spring Boot都有所了解了,我在該篇中也不再贅述,如果大家對Spring Boot有所興趣,可以在公眾號中留言,我會視情況而定。本文主要想講講配置文件相關的內容,你可能會比較疑惑,入門時期,最費時間的可能就是環境的配置
使用IDE創建工程正常情況都會生成一個 application.properties 文件,但我推薦使用YAML格式的 application.yml ,好處,誰用誰知道
例
girl:
height: 173
age: 20
cup: 64
注意:冒號后面一定要有一個空格
數組
languages:
- Ruby
- Perl
- Python
languages就是一個數組
變量引用
height: 178
decription: "my height is ${height}"
在decription中引用了height值
隨機數
my:
random:
- "${random.value}"
- "${random.int}"
- "${random.long}"
- "${random.int(10)}"
- "${random.int[10-30]}"
使用random就可以產生隨機數,可以有int、string、long等類型值
多環境配置
在實際開發中,肯定是存在開發、測試、線上多個環境的配置,如何解決這個問題
新建多個環境的配置文件,如: application-dev.yml、application-test.yml 等
在 application.yml 中加上
spring:
profiles:
active: dev
如上配置則會選用dev環境的配置文件
注意:在 application.yml 中的配置是適用所有的環境的
Java環境讀取配置變量
使用 @Value() 注解
@Value("${shareId}")
private String shareId;
如上,就獲取了shareId的值
使用 @ConfigurationProperties 注解
若存在多個相同的起點的配置變量
如
girl:
height: 173
age: 20
新建一個properties的java文件,用于注入
@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {
private Integer age;
private String height;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
}
在實際業務中,只要引用一下相應properties的java文件即可
@Autowired
private GirlProperties girlProperties;
松綁定
Spring Boot支持綁定的屬性不需要很嚴格的匹配約束
例
first-peron: Smith
在java文件中注入屬性可以是這樣子滴
@Component
public class Properties {
private String firstPerson;
public String getFirstPerson() {
return firstPerson;
}
public void setFirstPerson(String firstPerson) {
this.firstPerson = firstPerson;
}
}
來自:https://segmentfault.com/a/1190000008256545