简体   繁体   中英

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?

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)

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')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM