SpringBoot外部化配置使用Plus版的方法示例
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.properties
- classpath 下的 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是使用檔案系統的絕對和相對路徑的方式,這裡絕對路徑比較好理解 ,相對路徑則是從專案的根目錄作為相對目錄的
5是結合 SpEL 的表示式來使用的,可以直接從環境中獲取配置好的路徑。
以上幾種方式在實際開發中遇到和 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,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:/,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 物件中查詢配置項。
對一般使用來說,關注點就是配置檔案的位置,配置檔案的名,以及優先順序,這三個方面比較關心。
這篇記錄也基本能解答這幾個疑問,完成了寫這篇記錄的初衷。
到此這篇關於SpringBoot外部化配置使用Plus版的方法示例的文章就介紹到這了,更多相關SpringBoot外部化配置Plus版內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!