【问题标题】:How to overwrite Spring properties files in build directory?如何覆盖构建目录中的 Spring 属性文件?
【发布时间】:2016-12-14 21:44:12
【问题描述】:

我有一个 Spring Boot 和 Gradle 项目。我在 gradle.properties 文件中定义了应用程序版本,Gradle 可以从中读取它。我想在应用程序代码中有这个数字,作为@Value("${version}") 注入值。

我要做的是将版本号复制到 application.properties 或单独的 version.properties 文件中(均位于 src/main/resources.properties 中) 实际上,我想将属性文件加载到 Properties 对象中,设置“app.verion”属性,然后将其写出来。理想情况下,所有这些步骤都将在构建目录 ($buildDir/resources/main/version.properties) 中的文件上完成。这样我就不需要将这个动态设置的变量存储在 VCS 中。不幸的是,只有当我在源目录中编写属性文件时,这件事才有效。如果我尝试在构建中编辑那个,那么它没有任何效果。

你能帮帮我吗?我的任务应该什么时候运行?我感觉 Spring 可能会覆盖 build 中的文件。

我的代码是:

task appendVersionToApplicationProperties << {
    //  File versionPropsFile = new File("$buildDir/resources/main/version.properties")
    versionPropsFile.withWriter { w ->
        Properties p = new Properties()
        versionPropsFile.withInputStream {
            p.load(it)
        }
        p['app.version'] = appVersion // this is from gradle.properties
        p.store w, null
    }
}

build.finalizedBy(appendVersionToApplicationProperties)

gradle build 的输出:

$ gradle clean build
:clean
:compileJava
:compileGroovy UP-TO-DATE
:processResources
:appendVersionToApplicationProperties UP-TO-DATE
:classes
:findMainClass
:war
:bootRepackage
:assemble
:compileTestJava
:compileTestGroovy UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses
:test
:check
:build

BUILD SUCCESSFUL

Total time: 27.16 secs

【问题讨论】:

    标签: gradle spring-boot


    【解决方案1】:

    你可以这样做:

    task appendVersionToApplicationProperties {
        // write your properties
        // this is just basic groovy code
        Properties props = new Properties()
        props.put('app.version', appVersion) // get it from wherever
        def file = new File("$buildDir/resources/main/version.properties")
        file.createNewFile()
        props.store(file.newWriter(), null)
    }
    
    // this will run your task after the java compilation and resource processing
    processResources.finalizedBy appendVersionToApplicationProperties
    

    【讨论】:

    • 感谢您的回答!任务成功了,我测试了它单独运行。但是如果我运行 gradle clean build,version.properties 文件不在构建目录中。我想它被其中一项任务覆盖了,我只是不知道是哪一项。
    • @vargen_ 将 gradle 构建输出附加到您的问题,也许还有更多的 build.gradle 文件
    • 我添加了我的构建输出。我的 build.gradle 文件是一个基本的 Spring Boot 一加两个自定义任务,它们不在构建时运行。什么部分会很有趣?
    猜你喜欢
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    相关资源
    最近更新 更多