To-Do Calendar - Day24 讀取自定義的 Properties 檔案

在工作中,常常會有「預設值」或「功能開關」的要求,因有經常異動的可能性,通常會避免直接寫在程式中,改寫在外部設定檔中統一管理,這篇將以取得預設標籤顏色為例,演示如何讀取自定義的 properties,以及打包後啟動 JAR 檔時,引入外部設定檔。

建立自定義的 properties 設定檔

  • 在 resourses 目錄下建立 config 目錄,並配置 defaultValue.properties 檔案
    lable.firstColor=#ff9ebb
    lable.secondColor=#f5b8de
    lable.thirdColor=#f0d9a8
    lable.fourthColor=#68dddf
    

建立一個設定類的 class

  • 建立 defaultValueProperties class,並定義對應的屬性
    • @Configuration:表示這個 class 是用來設定的
    • @ConfigurationProperties:該註解用於綁定屬性
      • prefix:用來匹配屬性的前綴,也就是 defaultValue.properties 中的 「lable」
      • ignoreUnknownFields:用來告訴 Spring Boot 當有屬性不能匹配時是否要拋出異常
    • @PropertySource:設定文件的路徑
      @Configuration
      @ConfigurationProperties(prefix = "lable", ignoreUnknownFields = false)
      @PropertySource("classpath:config/defaultValue.properties")
      @Data
      public class DefaultValueProperties {
          private String firstColor;
          private String secondColor;
          private String thirdColor;
          private String fourthColor;
      }
    

注入設定檔的 Bean

  • 在要使用 defaultValue.properties 的地方(TodoListController class)注入 defaultValueProperties 的 Bean,就能直接在方法拿到設定檔的值了!

image

  • 運行結果
image

補充

實際照著 參考資料 做時,有發生下圖的錯誤,所以此篇的做法有些調整(拿掉 @EnableConfigurationProperties 註解),原因可能是在 spring 容器中有兩個 defaultValueProperties Bean,詳細可以看這篇《為什麼你的SpringBoot 自動配置失效了》:@EnableConfigurationProperties 的類,會默認註冊一個bean…

image

專案打包

  • Spring Boot 有內嵌 Tomcat,所以打包成 JAR 檔後可以直接啟動
  • 點開 IntelliJ 右側的 Maven 頁籤
  • 點 M 符號(Execute Maven Goal)按鈕
image
  • 執行 mvn clean package 指令
  • 完成後,會在專案的資料夾長出「target」資料夾,裡面有打包好的 JAR 檔

啟動時引入設定檔

  • 將 打包好的 JAR 檔、application.properties、defaultValue.properties 複製到作為運行的 build 資料夾
  • 在 build 資料夾打開命令提示字元,輸入啟動 JAR 檔的指令,並在後面添加選項,指定要引入的設定檔名稱與位置
    java -jar todoCalendar-0.0.1-SNAPSHOT.jar --spring.config.name=application,defaultValue --spring.config.location=./
    
image
  • 運行結果
    image

    取得使用者原子習慣列表

    image

    取得預設標籤顏色

    image

    實作 getLabelDefaultValue API 串接結果



延伸閱讀

參考資料

comments

comments powered by Disqus