Get value from `build.gradle` to code

末鹿安然 提交于 2019-12-11 18:19:11

问题


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?


回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/51669358/get-value-from-build-gradle-to-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!