Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from `build.gradle` to code

We have a build.gradle where the version is defined in it. I need to implement a version endpoint ( like /version) to get the version of the project. This version property in build.gradle has been there for a long time, I can't move it to the project.properties file. How can I access this version's values from my Java code?

like image 786
Milindu Sanoj Kumarage Avatar asked Dec 17 '25 20:12

Milindu Sanoj Kumarage


2 Answers

There are many ways with which you can "plant" information into your code

First you can use the manifest file, and read from it

jar {
  manifest {
    attributes(
      "lib-version": version
  }
}

With conjunction to Reading my own Jar's Manifest

The other option is to add that info the your property files before the jar task

task('addVersion') {
    doLast {
       //append the version here, see example
       file("src/main/resources/props.properties").append("version=$version")
    }
}
jar.dependsOn(addVersion)
like image 135
Boaz Avatar answered Dec 19 '25 11:12

Boaz


One of our project needs not only the version information but also build time etc. We use a copy task with template substitution.

task updateVersions(type: Copy) {
    Properties props = new Properties()
    props.load(new FileInputStream(file('build.properties')))
    props.put("buildtime", new Date().format("dd MMM yyyy hh:mm aa"))
    props.put("version", "${version}")
    from project(':main').file('Version.tmpl')
    into file('src/main/java').path
    expand(props)
    rename('Version.tmpl', 'Version.java')
}
like image 39
Dakshinamurthy Karra Avatar answered Dec 19 '25 11:12

Dakshinamurthy Karra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!