[Gradle] 利用profile 打包檔案

進行deployment 時, 總需要於properties 檔中進行設定, 除了容易出現人為錯誤, 而且費時失事. 在Maven 中, 可以透過修改pom.xml 進行profile 設定; 而Gradle 中, 亦有同樣的設定.

  1. 建立不同的profile 檔.
    於%PROJECT_HOME%/src/main/resources 中, 將原本的application.properties 複制數份, 並基於profile 命名如下.

    appication_<<ProfileName>>.properties

  2. 修改不同profile properties 檔設定並儲存.
  3. 設定複制設定.
    於build.gradle 中加入以下代碼.

    processResources {
        def defaultProfile = 'test'
        def profile = (project.hasProperty('profile') ? project.profile : defaultProfile).toLowerCase()
        println 'Profile: '+profile
        include "**/application_${profile}.properties"
        rename {
            'application.properties'
        }
    }

    在processResources() 中, 預設了test 為default profile, 若加入了profile 的話, 則會找出相對應的profile 取代原本的application.properties.

  4. 測試打包檔.
    於command prompt 中輸入以下指令:

    cd %PROJECT_DIR%
    gradlew build -Pprofile <<ProfileName>>

    參數-P 代表parameter, profile 則是profile 設定

  5. 檢查打包檔.
    利用解壓軟件打開打包檔, 打開WEB-INF/classes/application.properties, 若見到設定正確, 代表檔案複製成功. 
     
About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.