Java jar 的 Gradle 自定义任务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31031499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:32:47  来源:igfitidea点击:

Gradle custom task for jar

javagroovygradle

提问by CMPS

I am using Gradle for my Java project and I was wondering if it's possible to prevent gradle buildfrom creating a jar file each time executed.

我在我的 Java 项目中使用 Gradle,我想知道是否可以防止gradle build每次执行时都创建一个 jar 文件。

Also, is it possible to have a custom task for creating the Jar with dependencies at a specific location build/myAppJar/.

此外,是否可以在特定位置创建具有依赖项的 Jar 的自定义任务build/myAppJar/

Here's what I have so far for the custom task:

到目前为止,这是我对自定义任务的了解:

task toJar (type: Jar) {
    from configurations.compile.collect { zipTree it }
    manifest {
        attributes 'Implementation-Title': 'myApp',
                'Implementation-Version': 1.0,
                'Main-Class': mainClassName
    }
}

The above code will create the jar file under build/libs, and the file does not contain the compiled files, only the dependencies.

上面的代码会在 .jar 下创建 jar 文件build/libs,该文件不包含编译文件,只包含依赖项。

Thank you!

谢谢!

采纳答案by RaGe

The buildtask comes from the javaplugin. You can control when a jar is built with something like this:

build任务来自java插件。您可以控制何时使用以下内容构建 jar:

jar {
  onlyIf { condition }
}

You can set jar to be built when you declare something else to be true, or hard set it to false to never build a jar.

您可以在声明其他内容为 true 时将 jar 设置为构建,或者将其硬设置为 false 以从不构建 jar。

You can include sourcesets in your toJarcustom task, to include compiled files into your jar.

您可以在toJar自定义任务中包含源集,以将编译的文件包含到您的 jar 中。

task toJar (type: Jar) {
    from sourceSets.all
}

You are explicitly calling for all compile time dependencies to be included in the jar here: from configurations.compile.collect

您在此处明确要求将所有编译时依赖项包含在 jar 中: from configurations.compile.collect

ref: Gradle java plugin

参考:Gradle java 插件