本文以及收錄自springboot-guide(不僅是SpringBoot還有Spring重要知識點),地址:github.com/Snailclimb/… 。讓你學習 Spring 變的更加容易!若是以爲不錯的話,歡迎去點個 Star!html
不少時候咱們須要將一些經常使用的配置信息好比阿里雲 oss 配置、發送短信的相關信息配置等等放到配置文件中。java
下面咱們來看一下 Spring 爲咱們提供了哪些方式幫助咱們從配置文件中讀取這些配置信息。git
application.yml
內容以下:程序員
wuhan2020: 2020年初武漢爆發了新型冠狀病毒,疫情嚴重,可是,我相信一切都會過去!武漢加油!中國加油!
my-profile:
name: Guide哥
email: koushuangbwcx@163.com
library:
location: 湖北武漢加油中國加油
books:
- name: 天才基本法
description: 二十二歲的林朝夕在父親確診阿爾茨海默病這天,得知本身暗戀多年的校園男神裴之即將出國深造的消息——對方考取的學校,恰是父親當年爲她放棄的那所。
- name: 時間的秩序
description: 爲何咱們記得過去,而非將來?時間「流逝」意味着什麼?是咱們存在於時間以內,仍是時間存在於咱們之中?卡洛·羅韋利用詩意的文字,邀請咱們思考這一亙古難題——時間的本質。
- name: 了不得的我
description: 如何養成一個新習慣?如何讓心智變得更成熟?如何擁有高質量的關係? 如何走出人生的艱難時刻?
複製代碼
@value
讀取比較簡單的配置信息使用 @Value("${property}")
讀取比較簡單的配置信息:github
@Value("${wuhan2020}")
String wuhan2020;
複製代碼
須要注意的是
@value
這種方式是不被推薦的,Spring 比較建議的是下面幾種讀取配置信息的方式。web
@ConfigurationProperties
讀取並與 bean 綁定
LibraryProperties
類上加了@Component
註解,咱們能夠像使用普通 bean 同樣將其注入到類中使用。面試
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
@ToString
class LibraryProperties {
private String location;
private List<Book> books;
@Setter
@Getter
@ToString
static class Book {
String name;
String description;
}
}
複製代碼
這個時候你就能夠像使用普通 bean 同樣,將其注入到類中使用:spring
package cn.javaguide.readconfigproperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/** * @author shuang.kou */
@SpringBootApplication
public 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()); }
}
複製代碼
控制檯輸出:後端
湖北武漢加油中國加油
[LibraryProperties.Book(name=天才基本法, description........]
複製代碼
@ConfigurationProperties
讀取並校驗咱們先將application.yml
修改成以下內容,明顯看出這不是一個正確的 email 格式:安全
my-profile:
name: Guide哥
email: koushuangbwcx@
複製代碼
ProfileProperties
類沒有加@Component
註解。咱們在咱們要使用ProfileProperties
的地方使用@EnableConfigurationProperties
註冊咱們的配置 bean:
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")
@Validated
public class ProfileProperties {
@NotEmpty
private String name;
@Email
@NotEmpty
private String email;
//配置文件中沒有讀取到的話就用默認值
private Boolean handsome = Boolean.TRUE;
}
複製代碼
具體使用:
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());
}
}
複製代碼
由於咱們的郵箱格式不正確,因此程序運行的時候就報錯,根本運行不起來,保證了數據類型的安全性:
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
複製代碼
咱們把郵箱測試改成正確的以後再運行,控制檯就能成功打印出讀取到的信息:
ProfileProperties(name=Guide哥, email=koushuangbwcx@163.com, handsome=true)
複製代碼
@PropertySource
讀取指定 properties 文件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
@Setter
class WebSite {
@Value("${url}")
private String url;
}
複製代碼
使用:
@Autowired
private WebSite webSite;
System.out.println(webSite.getUrl());//https://javaguide.cn/
複製代碼
Spring 讀取配置文件也是有優先級的,直接上圖:
更對內容請查看官方文檔:docs.spring.io/spring-boot…
做者的其餘開源項目推薦: