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()
    }
})

猜你喜欢

转载自blog.csdn.net/qq631431929/article/details/53078778
今日推荐