常見的 spring boot 應用多是打包成 jar 包運行在服務器,這包含了一系列的配置文件以及第三方的依賴,不過這也引發了常見的思考:除application.properties
之外的其它配置文件變動,是否需要重新打包再重新部署?如日志配置文件、mybatis 的 xml 文件。
先來看看 Spring Boot 是如何加載核心配置文件的,在org.springframework.boot.context.config.ConfigFileApplicationListener
的內部類Loader
的load()
可以查看具體實現,以下優先級從高到低依次為:
通過啟動命令指定:
java -jar -Dspring.config.location=xxx/application.properties demo.jar
Jar 包同級目錄下的
config
目錄Jar 包同級目錄
classpath (
resources
) 同級目錄下的config
目錄classpath (
resources
) 目錄
留意到這段代碼定義:
// 默認的搜索路徑,對應了上面描述的優先級
private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/";
而 classpath 路徑是可以指定的,在Application
啟動類添加如下代碼,來看看默認的 jar 應用程序對應的 resources 位置:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println(DemoApplication.class.getResource("/"));
}
}
相應的輸出結果為:jar:file:/C:/xxx/demo.jar!/BOOT-INF/classes!/
因為java -jar
所指定及對應的優先級是最高的,所以啟動時設定 classpath 就可以達到想要的效果:將配置文件從 Jar 包獨立出來進行管理。
以下是該對應擴展方式的幾種說明:
-
-Xbootclasspath:
完全替換基本的 Java class 搜索路徑(不常用) -
-Xbootclasspath/p:
將 classpath 添加在核心class搜索路徑前面(不常用,避免引起沖突) -
-Xbootclasspath/a:
將classpath添加在核心class搜索路徑后面 (常用)
最后,這里通過指定當前目錄下的resources
文件夾進行了簡單測試:java -jar -Xbootclasspath/a:./resources/ demo.jar
,觀察啟動日志是否可以讀取 logback 配置:
相應的輸出及日志為:file:/C:/xxx/demo-project/target/resources/
,結果符合預期。
參考鏈接
文章已授權轉載,原文鏈接:如何在 Jar 包外管理 Spring Boot 應用的配置文件