Gradle构建的JavsWeb应用,如何在代码中获取build.gradle的version

如题。需求要求在登录页面显示web项目的版本号。

百度了很久没找到类似的问题,所以就来提问了~

build.gradle里面

group = 'Tomcat_Server'
version = '0.6.0-Debug'

sourceCompatibility = 1.8

想要在java代码(Controller层)中获取到“0.6.0-Debug”这个东西

最近我也想获取gradle里的version,思路来自里面注释的第二个连接,我将版本号生成到配置文件,java在读取配置文件就能每次打包程序都能获取最新版本信息

task('addVersion') {
    //https://my.oschina.net/lifj/blog/749345
    //https://stackoverflow.com/questions/51669358/get-value-from-build-gradle-to-code
    doLast {
        println("task addVersion")
        println("task ${version}")
        def myV = "${version}"
        //append the version here, see example
        //file("src/main/resources/application-build.properties").append("\nversion=jhd\n")
        //file("src/main/resources/application-build.properties").
        def filePath = 'src/main/resources/application-build.properties';
        Properties props = new Properties();
        props.load(new FileInputStream(file(filePath)))
        // props.put("buildtime", new Date().format("dd MMM yyyy hh:mm aa"))
        props.put("build.datetime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm")))
        //这里有个小问题,使用${}引用的变量是GStringImpl 不能传参给方法会出错,转成toString
        props.put("build.version", myV.toString())
        OutputStream out = new FileOutputStream(filePath)
        def comments = '#jhd auto make build info'
        //props.store(out, comments)
        props.store(new OutputStreamWriter(out, "utf-8"), comments)//解决乱码
    }
}
bootJar.dependsOn(addVersion)