How to get version attribute from a gradle build t

2020-06-08 03:28发布

问题:

I have a simple parent project with modules/applications within it. My build tool of choice is gradle. The parent build.gradle is defined below.

apply plugin: 'groovy'
dependencies {
    compile gradleApi()
    compile localGroovy()
}


allprojects {
    repositories {
        mavenCentral()
    }

    version "0.1.0-SNAPSHOT"
}

What I would like to do is utilize the version attribute (0.1.0-SNAPSHOT) within my swing application. Specifically, I'd like it to display in the titlebar of the main JFrame. I expect to be able to do something like this.setTitle("My Application - v." + ???.version);

The application is a plain java project, but I'm not opposed to adding groovy support it it will help.

回答1:

I like creating a properties file during the build. Here's a way to do that from Gradle directly:

task createProperties(dependsOn: processResources) {
  doLast {
    new File("$buildDir/resources/main/version.properties").withWriter { w ->
        Properties p = new Properties()
        p['version'] = project.version.toString()
        p.store w, null
    }
  }
}

classes {
    dependsOn createProperties
}


回答2:

You can always use brute force as somebody suggested and generate properties file during build. More elegant answer, which works only partially would be to use

getClass().getPackage().getImplementationVersion()

Problem is that this will work only if you run your application from generated jar - if you run it directly from IDE/expanded classes, getPackage above will return null. It is good enough for many cases - just display 'DEVELOPMENT' if you run from IDE(geting null package) and will work for actual client deployments.



回答3:

Better idea is to keep the project version in gradle.properties file. All the properties from this file will be automatically loaded and can be used in build.gradle script.

Then if you need the version in your swing application, add a version.properties file under src/main/resources folder and filter this file during application build, here is a post that shows how it should be done.

version.properties will be included in the final jar, hence can be read and via ClassLoader and properties from this file can be displayed in application.



回答4:

Simpler and updated solution of @Craig Trader (ready for Gradle 4.0/5.0)

task createProperties {
    doLast {
        def version = project.version.toString()
        def file = new File("$buildDir/resources/main/version.txt")
        file.write(version)
    }
}

war {
    dependsOn createProperties
}