Gradle: make build version available for Java

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

 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 specified here available for Java inline code? I would like to have a class like this in a project:

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

I guess this can be done with some kind of source code generation. Or letting gradle write the variable to some configuration file in src/main/resources . Is there a β€œstandard” (i.e. generally accepted) way to do this in Gradle?

+7
java build version gradle
source share
1 answer

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

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

Your code will be able to get the version from the jar manifest file:

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

Alternatively, write a Gradle task to create a properties file with a version in it and include this generated properties file in the jar file, then access it using getResouceAsStream() .

Of course, you can also generate the BuildVersion.java file from the Gradle task, with the version directly embedded in the string literal, and make sure that the task runs before the compile task.

But I would suggest just using the version number that you are about to include already (the manifest file), which has full support from both Gradle for writing and for the Java Runtime to read it without any custom Gradle job or reading the Java file.

+19
source share

All Articles