Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle: Make build version available to Java

By default, all gradle java projects have a version property. Typically, this looks something like:

allprojects {
    apply plugin: 'java'
    // ...

    // configure the group and version for this project
    group = 'org.example'
    version = '0.2-SNAPSHOT'
}

Is there a way to make the "version" property defined here available to the built java code? What I would like to have is a class like this in the project:

public class BuildVersion {

    public static String getBuildVersion(){
        return // ... what was configured in gradle when project was built
    }

}

I imagine that this could be done through some kind of source code generation. Or by letting gradle write the variable to some sort of config file in src/main/resources. Is there a "standard" (i.e. generally accepted) way to do this in Gradle?

like image 657
Alan47 Avatar asked Jun 05 '16 14:06

Alan47


People also ask

Which Gradle version is compatible with Java 11?

application'. > Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8. You can try some of the following options: - changing the IDE settings.


1 Answers

Assuming your Gradle script inserts the version into the jar manifest correctly, as shown here:

version = '1.0'
jar {
    manifest {
        attributes 'Implementation-Title': 'Gradle Quickstart',
                   'Implementation-Version': version
    }
}

Your code will be able to pick up the version from that jar manifest file:

public class BuildVersion {

    public static String getBuildVersion(){
        return BuildVersion.class.getPackage().getImplementationVersion();
    }

}

Alternatively, write a Gradle task for creating a property file with the version in it, and include that generated property file in the jar file, then access it using getResouceAsStream().

You could of course also generate the BuildVersion.java file from a Gradle task, with the version directly embedded as a string literal, and make sure the task runs before the compile task.

But I'd suggest just using the version number you're going to include already (manifest file), which has full support from both Gradle for writing it and Java Runtime for reading it, without any custom Gradle task or Java file reading.

like image 63
Andreas Avatar answered Oct 20 '22 05:10

Andreas