很多時候我們需要將一些常用的配置信息比如阿里雲 oss 配置、發送短信的相關信息配置等等放到配置文件中。
下面我們來看一下 Spring 爲我們提供了哪些方式幫助我們從配置文件中讀取這些配置信息。
application.yml內容如下:
wuhan2020: 2020年初武漢爆發了新型冠狀病毒,疫情嚴重,但是,我相信一切都會過去!武漢加油!中國加油!
my-profile:
name: Guide哥
email: [email protected]
library:
location: 湖北武漢加油中國加油
books:
- name: 天才基本法
description: 二十二歲的林朝夕在父親確診阿爾茨海默病這天,得知自己暗戀多年的校園男神裴之即將出國深造的消息——對方考取的學校,恰是父親當年爲她放棄的那所。
- name: 時間的秩序
description: 爲什麼我們記得過去,而非未來?時間“流逝”意味着什麼?是我們存在於時間之內,還是時間存在於我們之中?卡洛·羅韋利用詩意的文字,邀請我們思考這一亙古難題——時間的本質。
- name: 了不起的我
description: 如何養成一個新習慣?如何讓心智變得更成熟?如何擁有高質量的關係? 如何走出人生的艱難時刻?
1.通過@value讀取比較簡單的配置信息
使用@Value("${property}")讀取比較簡單的配置信息:
@Value("${wuhan2020}")
String wuhan2020;
“
需要注意的是@value這種方式是不被推薦的,Spring 比較建議的是下面幾種讀取配置信息的方式。
”
2.通過@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 一樣,將其注入到類中使用:
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........]
3.通過@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 protected], handsome=true)
4.@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/
5.題外話:Spring 加載配置文件的優先級
Spring 讀取配置文件也是有優先級的,直接上圖:
最後記得點贊+關注+轉發哦。謝謝支持,需要更多相關資料的可以私信“學習”免費獲取。
千萬不要把文章放在收藏夾吃灰哦。