首頁  >  文章  >  Java  >  Java Spring Boot中多環境設定檔的優先順序和方法是什麼?

Java Spring Boot中多環境設定檔的優先順序和方法是什麼?

PHPz
PHPz轉載
2023-04-22 23:28:062487瀏覽

    前言

    問題:springboot項目,開發環境、測試環境和生產環境設定檔如何分開表示?

    答案:多profile檔案方式

    1、多環境設定(profile)

    1.1、properties檔案設定

    #application.properties:主設定檔

    主設定檔設定決定載入哪個環境的設定檔

      spring.profiles.active=dev

    根據spring.profiles. active值,選擇載入不同環境配置

    application-{profile}.properties

    開發、測試、生產環境設定檔:

    • application-dev.properties:開發環境設定檔

    • application-test.properties:測試環境設定檔

    • application-prod.properties:生產環境設定檔

     1.2、YML檔案設定

    application.yml:主設定檔
    主設定檔設定決定載入哪個環境的設定檔

      spring:
          profiles:
              active:dev

    根據spring.profiles.active值,選擇載入不同環境配置

    application-{profile}.yml

    #開發、測試、生產環境設定檔:

    ## application-dev.yml:開發環境設定檔

    ##application-test.yml:測試環境設定檔

    application-prod.yml:生產環境設定檔

     1.3、修改主設定檔切換設定

    1.3.1、切換生產設定

    #默认配置
    server:
      port: 8080
    #切换配置
    spring:
      profiles:
        active: prod

    1.3.2、切換開發配置

    #开发环境配置
    server:
      port: 8080
    #切换配置
    spring:
      profiles:
        active: dev

    1.3.3、切換測試配置

    #测试环境配置
    server:
      port: 8080
    #切换配置
    spring:
      profiles:
        active: test

    1.4、命令列啟動設定檔

    1.4.1、命令列啟動設定檔
    • java -jar springboot-0.0.1-SNAPSHOT.jar--spring.profiles.active=dev

    • #1.4.2、虛擬機器參數啟動

    • java -Dspring.profiles.active=dev -jar springboot-0.0.1-SNAPSHOT.jar
    • #2、預設設定檔

    • Spring Boot啟動時會掃描下列5個位置的application.properties或apllication.yml文件,並將它們作為 Spring boot的預設設定檔。
    • file:./config/"/
    • #file:/config/

    file :./

    classpath:/config/

    • #classpath:/

    •  2.1、file

      指当前项目根目录;
    • 2.2、classpath
      • 指目前專案的類別路徑,即resources目錄。

        注意事項:
      • 位於相同位置的 application.properties 的優先權高於application.yml

    所有位置的檔案都會被加載,高優先權配置會覆寫低優先權配置,形成互補配置,也就是:

    存在相同的設定內容時,高優先順序的內容會覆寫低優先順序的內容;

    存在不同的設定內容時,高優先權和低優先權的設定內容取併集。

      # 3、外部設定檔
    • 可透過指定外部設定檔的路徑(預設設定檔失效)

    • 3.1、spring.config.location
    •   java -jar xxxx.jar --spring.config.location=外部文件

      3.2、spring.config.additional-location

    • 預設設定檔公共生效,其優先權是最高。.
    •  java -jar xxxx.jar --spring.config.additional-location=外部文件
      案例

      4、設定檔優先權

    • 以下是常用的 Spring Boot 設定形式及其載入順序(優先權由高到低)
    • 命令列參數

    設定檔(YAML檔、Properties檔)Java Spring Boot中多環境設定檔的優先順序和方法是什麼?

    ######@Configuration 註解類別上的@ PropertySource 指定的設定檔############透過 SpringApplication.setDefaultProperties指定的預設屬性############ 設定檔########### #

    以上是Java Spring Boot中多環境設定檔的優先順序和方法是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述:
    本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除