本文如有任何紕漏、錯誤,請不吝指正!
PS: 之前寫過一篇關于
SpringBoo中使用組態檔的一些姿勢,不過嘛,有句話(我)說的好:曾見小橋流水,未睹觀音坐蓮!所以再寫一篇增強版,以便記錄,
序言
上一篇博客記錄,主要集中在具體的配置內容,也就是使用@ConfigurationProperties這個注解來進行配置與結構化物件的系結,雖然也順帶說了下@Value的使用以及其區別,
在這篇記錄中,打算從總覽,鳥瞰的俯視視角,來從整體上對SpringBoot,乃至Spring Framework對于外部化組態檔處理,以及配置引數的系結操作,是如果處理的、怎么設計的,
這里其實主要說的是 SpringBoot,雖然@Value屬于Spring Framework的注解,不過在SpringBoot中也被頻繁使用,
SpringBoot版本: 2.2.6.RELEASE
SpringBoot啟動流程簡介
在SpringBoot的啟動程序中,大體上分為三步
第一步:prepareEnvironment,準備SpringBoot執行時所有的配置,
第二步:prepareContext,根據啟動時的傳入的配置類,創建其BeanDefinition,
第三步:refreshContext,真正啟動背景關系,
在這上面三步中,第一步結束后,我們所需要的或者組態檔配置的內容,大部分已經被加載進來,然后在第三步中進行配置的注入或者系結操作,
至于為什么是大部分,后面會有解釋,
將配置從組態檔加載到Environment中,使用的是事件通知的方式,
本篇博客記錄僅僅聚焦第一步中如何讀取組態檔的分析,順帶介紹下第三步的注入和系結,
受限于技術水平,僅能達到這個程度
外部化配置方式
如果有看到SpringBoot官網關于外部化配置的說明,就會驚訝的發現,原來SpringBoot有那么多的配置來源,
SpringBoot關于外部化配置特性的檔案說明,直達地址,
而實際使用中,通常可能會使用的比較多的是通過以下這些 方式
commandLine
通過在啟動jar時,加上-DconfigKey=configValue或者 --configKey=configValue的方式,來進行配置,多個配置項用空格分隔,
這種使用場景也多,只是一般用于一些配置內容很少且比較關鍵的配置,比如說可以決定運行環境的配置,
不易進行比較多的或者配置內容比較冗長的配置,容易出錯,且不便于維護管理,
application
這種是SpringBoot提供的,用于簡便配置的一種方式,只要我們將應用程式所用到的配置,直接寫到application.properties中,并將檔案放置于以下四個位置即可 ,
- 位于
jar同目錄的config目錄下的application.properties - 位于
jar同目錄的application.properties classpath下的config內application.propertiesclasspath下的application.properties
以上組態檔型別也都可以使用yml
默認情況下,這種方式是SpringBoot約定好的一種方式,檔案名必須為application,檔案內容格式可以為Yaml或者Properties,也許支持XML,因為看原始碼是支持的,沒有實踐,
好處就是簡單,省心省事,我們只需關注檔案本身的內容就可,其他的無需關心,這也是 SpringBoot要追求的結果,
缺點也很明顯,如果配置內容比較冗長,為了便于管理維護,增加可讀性,必須要對組態檔進行切分,通過功能等維度進行分類分組,使用多個組態檔來進行存放配置資料,
SpringBoot也想到了這些問題,因此提供了下面兩個比較方便的使用方式,來應對這種情況
profiles
profiles本身是也是一個配置項,它提供一種方式將部分應用程式配置進行隔離,并且使得它僅在具體某一個環境中可用,
具體實踐中常用的主要是針對不同的環境,有開發環境用到的特有配置值,有測驗環境特有的配置,有生產環境特有的配置,包括有些Bean根據環境選擇決定是否進行實體化,這些都是通過profiles來實作的,不過這里只關注配置這一塊內容,
它的使用方式通常是spring.profiles.active=dev,dev1或者 spring.profiles.include=db1,db2
這里可以看到有兩種不同的用法,這兩種方式是有區別的,
如果在application.properties中定義了一個spring.profiles.active=dev,而后在啟動時通過 命令列又寫了個 --spring.profiles.active=test,那么最終使用的是test,而不是dev,
如果同樣的場景下,使用spring.profiles.include來替換spring.profiles.active,那么結果會是dev和test都會存在,而不是替換的行為 ,
這就是兩個之間的差別,這種差別也使得他們使用的場景并不一樣,active更適合那些需要互斥的環境,而include則是多個并存的配置,
僅僅配置了profiles是沒有意義的,必須要有相應的組態檔配合一起使用,而且這些組態檔的命名要符合一定的規則,否則組態檔不會被加載進Environment的,
profiles檔案的命名規則為application-*.properties,同樣的,application.properties能放置的位置它也可以,不能的,它也不可以,
propery source
注解@PropertySource可以寫在配置類上,并且指定要讀取的組態檔路徑,這個路徑可以是絕對路徑,也可以是相對路徑,
它可以有以下幾種配置
@PropertySource("/config.properties")@PropertySource("config.properties")@PropertySource("file:/usr/local/config.properties")@PropertySource("file:./config.properties")@PropertySource("${pathPrefix}/config.properties")
其中1和2兩種方式是一樣的,都是從classpath去開始查找的
3和4是使用檔案系統的絕對和相對路徑的方式,這里絕對路徑比較好理解 ,相對路徑則是從專案的根目錄作為相對目錄的,如果是jar包的方式運行,就是jar所在的目錄,
5是結合SpEL的運算式來使用的,可以直接從環境中獲取配置好的路徑,
注意@PropertySource指定的檔案一定是要存在的,默認情況下檔案型別為Properties,可以通過自定義PropertySourceFactory來讀取其他的格式
FBI Warning : 第一種和第二種配置時,直接跑不會有問題,但是跑單元測驗時出了問題,建議加上
classpath:,原因在這里解釋
以上幾種方式在實際開發中遇到和SpringBoot相關的配置,基本都能應付過來了,
不過對于上面配置的一些原理性的內容,還沒有提到 ,下面會簡單說一下SpringBoot關于配置更詳細的處理,以及配置的優先級的問題,
原理淺入淺出
帶著問題去找原因,比較有目的性和針對性,效果也相對好一些,
所以這里描述幾個會引起疑問的現象
默認情況下自動加載的組態檔命名必須要是application
在使用application.properties時,可以同時在四個位置放置配置,配置的優先級就是上面羅列時顯示的優先級,同樣的配置,優先級高的生效,優先級低的忽略,
profiles引入的配置,也準守同樣的優先級規則
命令列配置具有最高優先級
有些配置不能使用@PropertySource的方式進行注入,比如日志的配置,
如果一個配置類使用了@ConfigurationProperties,然后欄位使用了@Value,@ConfigurationProperties先被處理,@Value后被處理,
原始碼簡讀
SpringBoot讀取application.properties配置
查看org.springframework.boot.context.config.ConfigFileApplicationListener的原始碼
public class ConfigFileApplicationListener implements EnvironmentPostProcessor, SmartApplicationListener, Ordered {
// Note the order is from least to most specific (last one wins)
// 默認檢索組態檔的路徑,優先級越來越高,
// 可以通過 spring.config.location重新指定,要早于當前類執行時配置好
private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/";
// 默認的配置名,可以通過命令列配置--spring.config.name=xxx來重新指定
// 不通過命令列也可以通過其他方式,環境變數這些,
private static final String DEFAULT_NAMES = "application";
private class Loader {
// 找到配置的路徑
private Set<String> getSearchLocations() {
if (this.environment.containsProperty(CONFIG_LOCATION_PROPERTY)) {
return getSearchLocations(CONFIG_LOCATION_PROPERTY);
}
Set<String> locations = getSearchLocations(CONFIG_ADDITIONAL_LOCATION_PROPERTY);
locations.addAll(
asResolvedSet(ConfigFileApplicationListener.this.searchLocations, DEFAULT_SEARCH_LOCATIONS));
return locations;
}
// 決議成Set
private Set<String> asResolvedSet(String value, String fallback) {
List<String> list = Arrays.asList(StringUtils.trimArrayElements(StringUtils.commaDelimitedListToStringArray(
(value != null) ? this.environment.resolvePlaceholders(value) : fallback)));
// 這里會做一個反轉,也就是配置的路徑中,放在后面的優先級越高
Collections.reverse(list);
return new LinkedHashSet<>(list);
}
private Set<String> getSearchNames() {
if (this.environment.containsProperty(CONFIG_NAME_PROPERTY)) {
String property = this.environment.getProperty(CONFIG_NAME_PROPERTY);
return asResolvedSet(property, null);
}
return asResolvedSet(ConfigFileApplicationListener.this.names, DEFAULT_NAMES);
}
}
}
命令列的配置具有最高優先級
protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) {
MutablePropertySources sources = environment.getPropertySources();
if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) {
sources.addLast(new MapPropertySource("defaultProperties", this.defaultProperties));
}
// 支持從命令列添加屬性以及存在引數時
if (this.addCommandLineProperties && args.length > 0) {
String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
// 這里是看下是不是存在同名的配置了
if (sources.contains(name)) {
PropertySource<?> source = sources.get(name);
CompositePropertySource composite = new CompositePropertySource(name);
composite.addPropertySource(
new SimpleCommandLinePropertySource("springApplicationCommandLineArgs", args));
composite.addPropertySource(source);
sources.replace(name, composite);
}
else {
// 直接添加,并且是添加到第一個位置,具有最高優先級
sources.addFirst(new SimpleCommandLinePropertySource(args));
}
}
}
@PropertySource是在refreshContext階段,執行BeanDefinitionRegistryPostProcessor時處理的
// org.springframework.context.annotation.ConfigurationClassParser#processPropertySource
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
String name = propertySource.getString("name");
if (!StringUtils.hasLength(name)) {
name = null;
}
String encoding = propertySource.getString("encoding");
if (!StringUtils.hasLength(encoding)) {
encoding = null;
}
// 獲取配置的檔案路徑
String[] locations = propertySource.getStringArray("value");
Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");
// 指定的讀取組態檔的工廠
Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
// 沒有就用默認的
PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));
// 回圈加載
for (String location : locations) {
try {
// 會決議存在占位符的情況
String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
// 使用DefaultResourceLoader來加載資源
Resource resource = this.resourceLoader.getResource(resolvedLocation);
// 創建PropertySource物件
addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
}
catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) {
// Placeholders not resolvable or resource not found when trying to open it
if (ignoreResourceNotFound) {
if (logger.isInfoEnabled()) {
logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
}
}
else {
throw ex;
}
}
}
}
因為執行時機的問題,有些配置不能使用@PropertySource,因為這個時候對有些配置來說,如果使用這種配置方式,黃花菜都涼了,同時這個注解要配合@Configuration注解一起使用才能生效,使用@Component是不行的,
處理@ConfigurationProperty的處理器是一個BeanPostProcessor,處理@Value的也是一個BeanPostProcessor,不過他倆的優先級并不一樣,
// @ConfigurationProperty
public class ConfigurationPropertiesBindingPostProcessor
implements BeanPostProcessor, PriorityOrdered, ApplicationContextAware, InitializingBean {
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE + 1;
}
}
// @Value
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
private int order = Ordered.LOWEST_PRECEDENCE - 2;
@Override
public int getOrder() {
return this.order;
}
}
從上面可以看出處理@ConfigurationProperty的BeanPostProcessor優先級很高,而@Value的BeanPostProcessor優先級很低,
使用@Value注入時,要求配置的key必須存在于Environment中的,否則會終止啟動,而@ConfigurationProperties則不會,
@Value可以支持SpEL運算式,也支持占位符的方式,
自定義配置讀取
org.springframework.boot.context.config.ConfigFileApplicationListener是一個監聽器,同時也是一個EnvironmentPostProcessor,在有ApplicationEnvironmentPreparedEvent事件觸發時,會去處理所有的EnvironmentPostProcessor的實作類,同時這些個實作也是使用SpringFactoriesLoader的方式來加載的,
對于組態檔的讀取,就是使用的這種方式,
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event);
}
if (event instanceof ApplicationPreparedEvent) {
onApplicationPreparedEvent(event);
}
}
private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {
List<EnvironmentPostProcessor> postProcessors = loadPostProcessors();
postProcessors.add(this);
AnnotationAwareOrderComparator.sort(postProcessors);
for (EnvironmentPostProcessor postProcessor : postProcessors) {
postProcessor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication());
}
}
有了這個擴展點后,我們就能自己定義讀取任何配置,從任何地方,
只要實作了EnvironmentPostProcessor介面,并且在META-INF/spring.factories中配置一下
org.springframework.boot.env.EnvironmentPostProcessor=com.example.configuration.ConfigurationFileLoader
附一個自己寫的例子
public class ConfigurationFileLoader implements EnvironmentPostProcessor {
private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/";
private static final String DEFAULT_NAMES = "download";
private static final String DEFAULT_FILE_EXTENSION = ".yml";
@Override
public void postProcessEnvironment (ConfigurableEnvironment environment,
SpringApplication application) {
List<String> list = Arrays.asList(StringUtils.trimArrayElements(
StringUtils.commaDelimitedListToStringArray(DEFAULT_SEARCH_LOCATIONS)));
Collections.reverse(list);
Set<String> reversedLocationSet = new LinkedHashSet(list);
ResourceLoader defaultResourceLoader = new DefaultResourceLoader();
YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
List<Properties> loadedProperties = new ArrayList<>(2);
reversedLocationSet.forEach(location->{
Resource resource = defaultResourceLoader.getResource(location + DEFAULT_NAMES+DEFAULT_FILE_EXTENSION);
if (resource == null || !resource.exists()) {
return;
}
yamlPropertiesFactoryBean.setResources(resource);
Properties properties = yamlPropertiesFactoryBean.getObject();
loadedProperties.add(properties);
});
Properties filteredProperties = new Properties();
Set<Object> addedKeys = new LinkedHashSet<>();
for (Properties propertySource : loadedProperties) {
for (Object key : propertySource.keySet()) {
String stringKey = (String) key;
if (addedKeys.add(key)) {
filteredProperties.setProperty(stringKey, propertySource.getProperty(stringKey));
}
}
}
PropertiesPropertySource propertySources = new PropertiesPropertySource(DEFAULT_NAMES, filteredProperties);
environment.getPropertySources().addLast(propertySources);
}
}
基本上都是 參考ConfigFileApplicationListener寫的 ,不過這里實作的功能,其實可以通過 @PropertySource來 解決,只是當時不知道,
使用@PropertySource的話,這么寫 @PropertySource("file:./download.properties") 即可,
個人猜測SpringBoot從配置中心加載配置就是使用的這個方式,不過由于沒有實際看過相關原始碼確認,不敢說一定是的 ,但是應該是八九不離十 的 ,
總結
這篇記錄寫的有點亂,一個是涉及到東西感覺也不少,還有就是本身有些地方不怎么了解,花費的時間不夠,
不過對SpringBoot的外部化配置來說,就是將各個途徑加載進來的配置,統一收歸Environment的MutablePropertySources欄位,這個欄位是一個ArrayList,保持添加進來時的順序,因此查找也是按照這個順序查找,查找時查到即回傳,不會完全遍歷所有的配置,除非遇到不存在的,
整個設計思想就是使用集中所有的配置,進行優先級排序,最后在有需要獲取配置的地方,從Environment物件中查找配置項,
對一般使用來說,關注點就是組態檔的位置,組態檔的名,以及優先級,這三個方面比較關心,
這篇記錄也基本能解答這幾個疑問,完成了寫這篇記錄的初衷,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/5213.html
標籤:其他
