簡體   English   中英

Spring 引導從 application.properties 中外部化屬性

[英]Spring Boot Externalize properties from within application.properties

我想將我的屬性源位置設置為從 application.propoerties 本身指向外部目錄。 我知道按如下方式傳遞命令行參數可以完成這項工作。

java -jar myApp.jar --spring.config.location=/Users/tony/Desktop/override.properties

但我想從應用程序本身設置此路徑,而不是傳遞命令行參數。 我嘗試將spring.config.location=/Users/tony/Desktop/override.properties添加到我的 application.properties 但它不起作用。

我怎樣才能做到這一點?

您可以嘗試在調用SpringApplication.run()的主要 class 中添加以下注釋:

@PropertySource("/Users/tony/Desktop/override.properties")

在運行 SpringBoot 應用程序時,它應該從那里獲取屬性。 Excluding the application.properties from src/main/resources using build - resources - resource - excludes - exclude in pom.xml would help to ensure that the packaged jar doesn't include the applcation.properties and would force Spring Boot to pick it up來自@PropertySource中指定的路徑

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <excludes>
                <exclude>**/application.properties</exclude>
            </excludes>
        </resource>
    </resources>
</build>

但請記住,通過這種方式,您正在創建屬性文件與應用程序的緊密耦合。 如果您將其保留為運行時參數,它將具有足夠的靈活性以在其他地方運行,並且維護也將更容易。

spring.config.locationspring.config.additional-location僅在設置為環境變量、系統屬性或命令行參數時有用。

指定要直接在application.properties文件中加載的其他配置文件的最佳方法是設置spring.config.import屬性,如下所示:

spring.config.import=file:/Users/tony/Desktop/override.properties

參考: https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-files

暫無
暫無

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

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