gradle - 如何覆盖构建目录中的 Spring 属性文件?

标签 gradle spring-boot

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

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

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

我的代码是:

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构建的输出:
$ 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

最佳答案

你可以这样做:

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 - 如何覆盖构建目录中的 Spring 属性文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41108686/

相关文章:

gradle - gradle任务-全部抛出错误

java - HTTP 状态 404 – 未找到 : for controller - no view resolvers found in Idea

java - 将 JSON 文档保留为字符串

gradlew 停留在监听传输 dt_socket 上

android - 当应用程序处于调试状态时,为什么 Gradle 在 Release模式下构建我的模块

android - Gradle:创建lib.aar文件后如何执行任务?

java - 无法转换为类 - 它们位于加载程序 'app' 的未命名模块中

logging - Spring Boot - 设置使用 Java Util Logging (jul) 的外部 jar 的日志记录级别

java - Pivot Cloud Foundry 错误 : "Browser detection failed and system property h2.browser not set" - Spring Boot 2

java - gradle:将 spring 应用程序迁移到多项目构建