1. 程式人生 > >gradle build 生成jar前替換配置檔案

gradle build 生成jar前替換配置檔案

第一次嘗試使用gradle,記錄一點經驗。

問題

用spring boot開發的新專案,開發環境和生產環境的application.properties不一致,每次build釋出前還得先改配置檔案。

方案
第一反應是google一下,但翻來覆去替換關鍵詞,也沒有搜到恰當的方案,只能自己動手了。

首先考慮到的在build時在腳本里讀寫properties檔案動態替換內容,但這樣太不符合我的審美,於是把生產環境的配置單獨做了個application.properties.real檔案,與開發環境的application.properties檔案並列放在resource目錄下。觀察到build打jar包其實是把build/classes/main和build/resources/main目錄合併打包完事,於是在jar任務中添加了一個替換配置檔案的前置任務:

jar {
    baseName = 'app'
    manifest {
        attributes 'Implementation-Title': 'app', 'Implementation-Version': version
    }

    def app_config="build/resources/main/application.properties"
    def local_config="build/resources/main/application.properties.local"
    def real_config="build/resources/main/application.properties.real"
    doFirst {
        project.file(app_config).renameTo(local_config)
        project.file(real_config).renameTo(app_config)
    }
}

上面適合在生產環境構建的情況。如果在本地構建的話,替換檔案後test cases由於配置檔案問題無法通過,所以需要在jar包打完後把配置檔案改回來,完整程式碼如下

jar {
    baseName = 'app'
    manifest {
        attributes 'Implementation-Title': 'app', 'Implementation-Version': version
    }

    def app_config="build/resources/main/application.properties"
    def local_config="build/resources/main/application.properties.local"
    def real_config="build/resources/main/application.properties.real"
    doFirst {
        project.file(app_config).renameTo(local_config)
        project.file(real_config).renameTo(app_config)
    }
    doLast {
        project.file(app_config).renameTo(real_config)
        project.file(local_config).renameTo(app_config)
    }
}

測試通過,提交了事:-D

-----------------------------------------------------------------------------------------------------------------------------------------------------------

補記@2018/04/25

以前的做法不夠好,更好的做法為生成jar時替換檔案,例如

def runtimeFolder = "src/runtime_resources"
jar.duplicatesStrategy=DuplicatesStrategy.FAIL
jar.from(runtimeFolder)
def fileList=new ArrayList<String>();
fileTree(runtimeFolder).each { f -> fileList.add(f.name)}
jar.filesMatching(fileList,{ p ->
    if('main'.equals(p.file.parentFile.name)){
        p.exclude()
    }
})