一、概述
Properties 檔案是我們可以用來存盤專案特定資訊的常用方法,理想情況下,我們應該將其保留在 jar 包之外,以便能夠根據需要對配置進行更改,
在這個教程中,我們將研究在 Spring Boot 應用程式 中從 jar 外部位置加載 Properties 檔案的各種方法,
二、使用默認位置
按照慣例,Spring Boot 按以下優先順序在四個預定位置查找外部化組態檔 --- application.properties 或 application.yml :{#crayon-5c73a186c8530009937282}
- 當前目錄的 /config 子目錄
- 當前目錄
- 一個類路徑 /config 包
- 類路徑根
因此,在 application.properties 中定義并放置在當前目錄的 /config 子目錄中的屬性將被加載, 這也會在發生沖突時覆寫其他位置的屬性,
三、使用命令列
如果上述約定對我們不起作用,我們可以直接在命令列中配置位置:
java -jar app.jar --spring.config.location=file:///Users/home/config/jdbc.properties
我們還可以傳遞應用程式搜索檔案的檔案夾位置:
java -jar app.jar --spring.config.name=application,jdbc --spring.config.location=file:///Users/home/config
最后,另一種方法是通過 Maven 插件 運行 Spring Boot 應用程式,
在那里,我們可以使用 -D 引數:
mvn spring-boot:run -Dspring.config.location="file:///Users/home/jdbc.properties"
四、使用環境變數
現在假設我們不能更改啟動命令,
很棒的是 Spring Boot 還會讀取環境變數 SPRING_CONFIG_NAME 和 SPRING_CONFIG_LOCATION:
export SPRING_CONFIG_NAME=application,jdbc
export SPRING_CONFIG_LOCATION=file:///Users/home/config
java -jar app.jar
請注意,仍將加載默認檔案,但是環境特定的屬性檔案優先以防發生屬性沖突,
- 使用應用程式屬性
如我們所見,我們必須在應用程式啟動之前定義 spring.config.name 和 spring.config.location 屬性,因此在 application.properties 檔案(或 YAML 對應檔案)中使用它們將沒有影響,
Spring Boot 在 2.4.0 版本中修改了屬性的處理方式,
與此更改一起,團隊引入了一個新屬性,允許直接從應用程式屬性匯入其他組態檔:
spring.config.import=file:./additional.properties,optional:file:/Users/home/config/jdbc.properties
- 以編程方式
如果我們想要編程訪問,我們可以注冊一個 PropertySourcesPlaceholderConfigurer bean:
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer properties =
new PropertySourcesPlaceholderConfigurer();
properties.setLocation(new FileSystemResource("/Users/home/conf.properties"));
properties.setIgnoreResourceNotFound(false);
return properties;
}
在這里,我們使用 PropertySourcesPlaceholderConfigurer 從自定義位置加載屬性,
七、從 Fat Jar 中排除檔案
Maven Boot 插件會自動將 src/main/resources 目錄下的所有檔案包含到 jar 包中,
如果我們不想讓某個檔案成為 jar 的一部分,我們可以使用一個簡單的配置來排除它:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>**/conf.properties</exclude>
</excludes>
</resource>
</resources>
</build>
在這個例子中,我們過濾掉了 conf.properties 檔案,使其不包含在生成的 jar 中,
八、小結
本文展示了 Spring Boot 框架本身如何為我們處理 externalized configuration,
通常,我們只需要將屬性值放在正確的檔案和位置,但我們也可以使用 Spring 的 Java API 進行更多控制,
與往常一樣,示例的完整源代碼可在 GitHub 上 獲得,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/514165.html
標籤:其他
