Reputation: 2790
I have a Spring Boot and Gradle project. I defined the app version in the gradle.properties file from where Gradle can read it. I'd like to have this number in the application code, as a @Value("${version}")
injected value.
What I am trying to do is to copy the version number into application.properties or a separate version.properties file (both located in src/main/resources. Actually, I want to load the properties file into a Properties object, set the 'app.verion' property and then write it out. Ideally all these steps would be done on the file in the build dir ($buildDir/resources/main/version.properties). This way I don't need to store this dinamically set variable in the VCS. Unfortunately the thing only works if I write the properties file in the source directory. If I try to edit the one in build, then it doesn't have any effect.
Could you help me? When should my task ran? I have the feeling that Spring might overwrite the file in build.
My code is:
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)
Output of 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
Upvotes: 1
Views: 2014
Reputation: 51481
You can do this:
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
Upvotes: 2