Gradle:使构建版本可用于Java [英] Gradle: Make build version available to Java

查看:85
本文介绍了Gradle:使构建版本可用于Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,所有gradle java项目都具有version属性.通常,这看起来像:

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

allprojects {
    apply plugin: 'java'
    // ...

    // configure the group and version for this project
    group = 'org.example'
    version = '0.2-SNAPSHOT'
}

是否有一种方法可以使此处定义的版本"属性对构建的Java代码可用?我想要的是项目中的此类课程:

Is there a way to make the "version" property defined here available to the built java code? What I would like to have is a class like this in the project:

public class BuildVersion {

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

}

我想这可以通过某种源代码生成来完成.或者通过让gradle将变量写入src/main/resources中的某种配置文件中.在Gradle中是否有标准"(即通常被接受)的方式来做到这一点?

I imagine that this could be done through some kind of source code generation. Or by letting gradle write the variable to some sort of config file in src/main/resources. Is there a "standard" (i.e. generally accepted) way to do this in Gradle?

推荐答案

假设您的Gradle脚本正确地将version插入jar清单中,如

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

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

您的代码将能够从该jar清单文件中提取版本:

Your code will be able to pick up the version from that jar manifest file:

public class BuildVersion {

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

}

或者,编写一个Gradle任务来创建带有版本的属性文件,并将生成的属性文件包含在jar文件中,然后使用getResouceAsStream()访问它.

Alternatively, write a Gradle task for creating a property file with the version in it, and include that generated property file in the jar file, then access it using getResouceAsStream().

您当然也可以从Gradle任务生成BuildVersion.java文件,并将该版本直接作为字符串文字嵌入,并确保该任务在compile任务之前运行.

You could of course also generate the BuildVersion.java file from a Gradle task, with the version directly embedded as a string literal, and make sure the task runs before the compile task.

但是我建议您仅使用将要包含的版本号(清单文件),该版本号完全受Gradle的支持,并得到Java Runtime的完全支持,而无需任何自定义的Gradle任务或Java文件阅读.

But I'd suggest just using the version number you're going to include already (manifest file), which has full support from both Gradle for writing it and Java Runtime for reading it, without any custom Gradle task or Java file reading.

这篇关于Gradle:使构建版本可用于Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆