很多時候我們需要將一些常用的配置信息比如阿里雲 oss 配置、發送短信的相關信息配置等等放到配置文件中。
下面我們來看一下 Spring 為我們提供了哪些方式幫助我們從配置文件中讀取這些配置信息。
application.yml 內容如下:
<code>wuhan2020: 2020年初武漢爆發了新型冠狀病毒,疫情嚴重,但是,我相信一切都會過去!武漢加油!中國加油!my-profile: name: Guide哥 email: [email protected]: location: 湖北武漢加油中國加油 books: - name: 天才基本法 description: 二十二歲的林朝夕在父親確診阿爾茨海默病這天,得知自己暗戀多年的校園男神裴之即將出國深造的消息——對方考取的學校,恰是父親當年為她放棄的那所。 - name: 時間的秩序 description: 為什麼我們記得過去,而非未來?時間“流逝”意味著什麼?是我們存在於時間之內,還是時間存在於我們之中?卡洛·羅韋利用詩意的文字,邀請我們思考這一亙古難題——時間的本質。 - name: 了不起的我 description: 如何養成一個新習慣?如何讓心智變得更成熟?如何擁有高質量的關係? 如何走出人生的艱難時刻?/<code>
1.通過 @value 讀取比較簡單的配置信息
使用 @Value("${property}") 讀取比較簡單的配置信息:
<code>@Value("${wuhan2020}")String wuhan2020;/<code>
需要注意的是 @value這種方式是不被推薦的,Spring 比較建議的是下面幾種讀取配置信息的方式。
2.通過@ConfigurationProperties讀取並與 bean 綁定
LibraryProperties 類上加了 @Component 註解,我們可以像使用普通 bean 一樣將其注入到類中使用。
<code>import lombok.Getter;import lombok.Setter;import lombok.ToString;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Configuration;import org.springframework.stereotype.Component;import java.util.List;@Component@ConfigurationProperties(prefix = "library")@Setter@Getter@ToStringclass LibraryProperties { private String location; private List<book> books; @Setter @Getter @ToString static class Book { String name; String description; }}/<book>/<code>
這個時候你就可以像使用普通 bean 一樣,將其注入到類中使用:
<code>package cn.javaguide.readconfigproperties;import org.springframework.beans.factory.InitializingBean;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * @author shuang.kou */@SpringBootApplicationpublic class ReadConfigPropertiesApplication implements InitializingBean { private final LibraryProperties library; public ReadConfigPropertiesApplication(LibraryProperties library) { this.library = library; } public static void main(String[] args) { SpringApplication.run(ReadConfigPropertiesApplication.class, args); } @Override public void afterPropertiesSet() { System.out.println(library.getLocation()); System.out.println(library.getBooks()); }}/<code>
控制檯輸出:
<code>湖北武漢加油中國加油[LibraryProperties.Book(name=天才基本法, description........]/<code>
3.通過@ConfigurationProperties讀取並校驗
我們先將application.yml修改為如下內容,明顯看出這不是一個正確的 email 格式:
<code>my-profile: name: Guide哥 email: koushuangbwcx@/<code>
ProfileProperties 類沒有加 @Component 註解。我們在我們要使用ProfileProperties 的地方使用@EnableConfigurationProperties註冊我們的配置 bean:
<code>import lombok.Getter;import lombok.Setter;import lombok.ToString;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;import org.springframework.validation.annotation.Validated;import javax.validation.constraints.Email;import javax.validation.constraints.NotEmpty;/*** @author shuang.kou*/@Getter@Setter@ToString@ConfigurationProperties("my-profile")@Validatedpublic class ProfileProperties { @NotEmpty private String name; @Email @NotEmpty private String email; //配置文件中沒有讀取到的話就用默認值 private Boolean handsome = Boolean.TRUE;}/<code>
具體使用:
<code>package cn.javaguide.readconfigproperties;import org.springframework.beans.factory.InitializingBean;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.context.properties.EnableConfigurationProperties;/** * @author shuang.kou */@SpringBootApplication@EnableConfigurationProperties(ProfileProperties.class)public class ReadConfigPropertiesApplication implements InitializingBean { private final ProfileProperties profileProperties; public ReadConfigPropertiesApplication(ProfileProperties profileProperties) { this.profileProperties = profileProperties; } public static void main(String[] args) { SpringApplication.run(ReadConfigPropertiesApplication.class, args); } @Override public void afterPropertiesSet() { System.out.println(profileProperties.toString()); }}/<code>
因為我們的郵箱格式不正確,所以程序運行的時候就報錯,根本運行不起來,保證了數據類型的安全性:
<code>Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'my-profile' to cn.javaguide.readconfigproperties.ProfileProperties failed: Property: my-profile.email Value: koushuangbwcx@ Origin: class path resource [application.yml]:5:10 Reason: must be a well-formed email address/<code>
我們把郵箱測試改為正確的之後再運行,控制檯就能成功打印出讀取到的信息:
<code>ProfileProperties(name=Guide哥, [email protected], handsome=true)/<code>
4.@PropertySource讀取指定 properties 文件
<code>import lombok.Getter;import lombok.Setter;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Component;@Component@PropertySource("classpath:website.properties")@Getter@Setterclass WebSite { @Value("${url}") private String url;}/<code>
使用:
<code>@Autowiredprivate WebSite webSite;System.out.println(webSite.getUrl());//https://javaguide.cn//<code>
5.題外話:Spring 加載配置文件的優先級
Spring 讀取配置文件也是有優先級的,直接上圖:
更對內容請查看官方文檔:docs.spring.io/spring-boot…
本文源碼:github.com/Snailclimb/…
作者:SnailClimb
鏈接:https://juejin.im/post/5e3f7a65f265da5732551b0a
閱讀更多 Java架構師阿谷 的文章