簡體   English   中英

從命令行設置彈簧屬性文件位置

[英]Set spring properties file location from command line

我有一個簡單的 Spring 應用程序,可以從屬性文件中讀取配置值。 默認情況下,該文件配置為位於類路徑上(配置類上的@PropertySource("classpath:thefile.properties")注釋)。 我希望能夠有選擇地使用其他一些我可以(但不必)在程序啟動時在命令行中指定的屬性文件。 即,我最終想要運行這樣的東西:

java -jar application.jar --path "some/location/thefile.properties"

現在應該使用來自指定文件的值。

我已經嘗試在 jar 之前和之后使用 SpringBoot 和spring.config.location選項:

java -jar "-Dspring.config.location=file:some/location/thefile.properties" application.jar
  • 繼續使用類路徑上文件中的值
java -jar application.jar "--spring.config.location=file:some/location/thefile.properties"
  • 抱怨無法識別的選項

我的主類看起來像這樣:

@SpringBootApplication
public class MainClass {
    public static void main(String[] args) {
        SpringApplication.run(MainClass.class, args);
        // Application code triggered here...
    }
}

我不需要使用 SpringBoot,我只想以某種方式設置屬性文件位置。 任何的想法? 這可能嗎?

在你的財產類上做這樣的事情:

 @Configuration
 @PropertySource(value = "file:${myapp.external.config}")

 **Command**  java -jar -Dmyapp.external.config="C:\yourPath\abc.properties" xyz.jar

如果您有多個外部屬性文件,請參見下面的示例

 @Configuration
 @PropertySource(value = {"file:${app1.config}", "file:${app2.config}"})

 **Command**  java -jar -Dapp1.config="C:\yourPath\abc1.properties" 
                        -Dapp2.config="C:\yourPath\abc2.properties" xyz.jar

這在 Windows 上對我"C:\\Program Files\\Java\\jdk-15.0.1\\bin\\java" -jar C:\\Users\\your.name\\YourApp.jar --spring.config.location="C:/Users/your.name/yourAppProps.properties""C:\\Program Files\\Java\\jdk-15.0.1\\bin\\java" -jar C:\\Users\\your.name\\YourApp.jar --spring.config.location="C:/Users/your.name/yourAppProps.properties"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM