![](/img/trans.png)
[英]Pom file configuration to package external/custom jar file in the fat spring boot executable jar file
[英]Spring Boot executable jar and external configuration file
我有一個使用第三方jar的Spring Boot應用程序。 這個jar需要一個xml配置文件,該文件必須由客戶端在運行時(單獨)提供,並且不能預先打包。 第三方lib使用以下序列加載該文件( if
s和null檢查我被剝離):
FileConfigurator.class.getResource("/" + filename);
Thread.currentThread().getContextClassLoader().getResource("/" + filename);
Thread.currentThread().getContextClassLoader().getResource(filename);
我無法改變lib加載文件的方式(例如使用Spring的資源加載),所以它必須在classpath上。 因此,我似乎失去了像java -jar my-spring-boot-app.jar
那樣執行它的可能性,因為-jar
選項可以防止添加任何其他類路徑條目。 所以我開始像運行它一樣
java -classpath my-spring-boot-app.jar:./config/: org.springframework.boot.loader.JarLauncher
我的目錄結構如下:
|-- config
| |-- application.properties
| `-- 3rd-party-config.xml
|-- my-spring-boot-app.jar
但是Spring的自動裝配開始失敗:config目錄中的其他application.properties
文件覆蓋了一些設置,使用上面的命令導致app啟動失敗:
創建名為“ORBConfig”的bean時出錯:注入自動連接的依賴項失敗; 嵌套異常是org.springframework.beans.factory.BeanCreationException:無法自動裝配字段:private java.lang.String com.company.app.communication.corba.orb.ORBConfig.serverName; 嵌套異常是java.lang.IllegalArgumentException:無法在字符串值“$ {application.corba.serverName}”中解析占位符'application.corba.serverName'
字段String serverName
使用@Value("${application.corba.serverName}")
批注,該屬性在JAR中捆綁的application.properties
文件中定義,並且當config dir中不存在其他application.properties
時,值注入工作正常。
我的實際問題是:部署和/或運行Spring Boot應用程序的可行方法是什么,利用可執行的Jar功能,在運行時提供額外的類路徑資源,仍然能夠通過classpath application.properties
覆蓋一些(但不是全部)屬性application.properties
文件?
應用程序使用spring boot maven插件打包,並使用spring-boot-starter-parent
父POM。
如果您不更改啟動命令,一個簡單的答案:
將
./config/application.properties
移動到./config/config/application.properties
如果存在多個具有相同名稱的類路徑資源,則Spring Boot將僅加載其中一個,在本例中,Spring Boot加載並優先考慮屬性資源,如下所示:
file:config/application.properties
classpath:application.properties
,可以解析為my-spring-boot-app.jar!/applcation.properties
或./config/application.properties
如果您的classLoader選擇./config/application.properties
作為第二個屬性源。 砰!
Spring Boot的默認配置屬性資源路徑優先級(從最高到最低的優先級)是:
file:config/
file:
classpath:config/
classpath
普通的可執行jar執行使這兩個配置屬性落入:
file:config/application.properties
classpath:application.properties
(來自jar) 將./config/application.propertie
移動到'./config/config/application.properties'會變為:
classpath:config/application.properties
classpath:application.properties
(來自jar) 兩者都以相同的順序而且沒有歧義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.