A Custom Task in Gradle – Gradle中的一个自定义任务

最后修改: 2018年 3月 5日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we’ll cover how to create a custom task in Gradle. We’ll show a new task definition using a build script or a custom task type.

在这篇文章中,我们将介绍如何在Gradle中创建一个自定义任务。我们将展示一个使用构建脚本或自定义任务类型的新任务定义。

For the introduction to the Gradle, please see this article. It contains the basics of Gradle and – what’s the most important for this article – the introduction to Gradle tasks.

关于Gradle的介绍,请看这篇文章。它包含了Gradle的基础知识和–对本文来说最重要的是–Gradle任务的介绍。

2. Custom Task Definition Inside build.gradle

2.在build.gradle内自定义任务定义

To create a straightforward Gradle task, we need to add its definition to our build.gradle file:

要创建一个直接的Gradle任务,我们需要将其定义添加到我们的build.gradle文件中。

task welcome {
    doLast {
        println 'Welcome in the Baeldung!'
    }
}

The main goal of the above task is just to print text “Welcome in the Baeldung!”. We can check if this task is available by running gradle tasks –all command:

上述任务的主要目标只是打印文本 “Welcome in the Baeldung!” 。我们可以通过运行gradle tasks -all命令来检查这个任务是否可用

gradle tasks --all

The task is on the list under the group Other tasks:

该任务在其他任务组下的列表中。

Other tasks
-----------
welcome

It can be executed just like any other Gradle task:

它可以像任何其他Gradle任务一样被执行。

gradle welcome

The output is as expected – the “Welcome in the Baeldung!” message.

输出结果和预期的一样–“欢迎来到Baeldung!”信息。

Remark: if option –all is not set, then tasks which belong to “Other” category aren’t visible. Custom Gradle task can belong to a different group than “Other” and can contain a description.

备注:如果没有设置-all选项,那么属于 “其他 “类别的任务就不可见。自定义Gradle任务可以属于与 “其他 “不同的组,并且可以包含一个描述。

3. Set Group and Description

3.设置组别和说明

Sometimes it’s handy to group tasks by function, so they are visible under one category. We can quickly set group for our custom tasks, just by defining a group property:

有时,按功能对任务进行分组是很方便的,这样它们就可以在一个类别下看到。我们可以为我们的自定义任务快速设置组,只需定义一个组属性

task welcome {
    group 'Sample category'
    doLast {
        println 'Welcome on the Baeldung!'
    }
}

Now when we run Gradle command to list all available tasks (–all option isn’t needed anymore), we’ll see our task under new group:

现在当我们运行Gradle命令列出所有可用的任务时(-all选项不再需要),我们会在新组下看到我们的任务。

Sample category tasks
---------------------
welcome

However, it’s also beneficial for others to see what a task is responsible for. We can create a description which contains short information:

然而,这也有利于其他人看到一项任务所负责的内容。我们可以创建一个描述,其中包含简短的信息。

task welcome {
    group 'Sample category'
    description 'Tasks which shows a welcome message'
    doLast {
        println 'Welcome in the Baeldung!'
    }
}

When we print a list of the available tasks the output will be as follow:

当我们打印一个可用的任务列表时,输出结果将如下。

Sample category tasks
---------------------
welcome - Tasks which shows a welcome message

This kind of task definition is called ad-hoc definition.

这种任务定义被称为临时性定义

Coming further, it’s beneficial to create a customizable task which definition can be reused. We’ll cover how to create a task from a type and how to make some customization available to the users of this task.

进一步说,创建一个可定制的任务是有益的,其定义可以被重复使用。我们将介绍如何从一个类型中创建一个任务,以及如何为这个任务的用户提供一些定制服务。

4. Define Gradle Task Type Inside build.gradle

4.在 build.gradle内定义Gradle任务类型

The above “welcome” task cannot be customized, thus, in most cases, it’s not very useful. We can run it, but if we need it in a different project (or subproject), then we need to copy and paste its definition.

上述 “欢迎 “任务不能被定制,因此,在大多数情况下,它不是很有用。我们可以运行它,但如果我们在不同的项目(或子项目)中需要它,那么我们需要复制和粘贴其定义。

We can quickly enable customization of the task by creating a task type. Merely, a task type is defined inside the build script:

我们可以通过创建一个任务类型来快速实现任务的定制化。简单地说,任务类型是在构建脚本里面定义的。

class PrintToolVersionTask extends DefaultTask {
    String tool

    @TaskAction
    void printToolVersion() {
        switch (tool) {
            case 'java':
                println System.getProperty("java.version")
                break
            case 'groovy':
                println GroovySystem.version
                break
            default:
                throw new IllegalArgumentException("Unknown tool")
        }
    }
}

A custom task type is a simple Groovy class which extends DefaultTask – the class which defines standard task implementation. There are other task types which we can extend from, but in most cases, the DefaultTask class is the appropriate choice.

自定义任务类型是一个简单的Groovy类,它扩展了DefaultTask–定义标准任务实现的类。还有其他任务类型,我们可以从中扩展,但在大多数情况下,DefaultTask类是合适的选择。

PrintToolVersionTask task contains tool property which can be customized by instances of this task:

PrintToolVersionTask 任务包含可由该任务的实例定制的工具属性

String tool

We can add as many properties as we want – keep in mind it is just a simple Groovy class field.

我们可以添加任意多的属性–请记住这只是一个简单的Groovy类字段。

Additionally, it contains method annotated with @TaskAction. It defines what this task is doing. In this simple example it prints version of installed Java or Groovy – depends on the given parameter value.

此外,它还包含@TaskAction注释的方法。它定义了这个任务正在做什么。在这个简单的例子中,它打印出安装的Java或Groovy的版本–取决于给定的参数值。

To run a custom task based on created task type we need to create a new task instance of this type:

要运行一个基于创建的任务类型的自定义任务,我们需要创建一个该类型的新任务实例

task printJavaVersion(type : PrintToolVersionTask) {
    tool 'java'
}

The most important parts are:

最重要的部分是。

  • our task is a PrintToolVersionTask type, so when executed it’ll trigger the action defined in the method annotated with @TaskAction
  • we added a customized tool property value (java) which will be used by PrintToolVersionTask

When we run the above task the output is as expected (depends on the Java version installed):

当我们运行上述任务时,输出结果与预期一致(取决于安装的Java版本)。

> Task :printJavaVersion 
9.0.1

Now let’s create a task which prints the installed version of Groovy:

现在让我们创建一个任务,打印已安装的Groovy的版本。

task printGroovyVersion(type : PrintToolVersionTask) {
    tool 'groovy'
}

It uses the same task type as we defined before, but it has a different tool property value. When we execute this task it prints the Groovy version:

它使用的任务类型与我们之前定义的相同,但它有一个不同的工具属性值。当我们执行这个任务时,它会打印出Groovy版本。

> Task :printGroovyVersion 
2.4.12

If we have not too many custom tasks, then we can define them directly in the build.gradle file (like we did above). However, if there are more than a few then our build.gradle file becomes hard to read and understand.

如果我们没有太多的自定义任务,那么我们可以直接在build.gradle文件中定义它们(就像我们上面做的)。但是,如果超过了几个,那么我们的build.gradle文件就会变得难以阅读和理解。

Luckily, Gradle provides some solutions for that.

幸运的是,Gradle为此提供了一些解决方案。

5. Define Task Type in the buildSrc Folder

5.在buildSrc文件夹中定义任务类型

We can define task types in the buildSrc folder which is located at the root project level. Gradle compiles everything that is inside and adds types to the classpath so our build script can use it.

我们可以buildSrc文件夹中定义任务类型,该文件夹位于项目根层。Gradle会编译里面的所有东西,并将类型添加到classpath中,这样我们的构建脚本就可以使用它。

Our task type which we defined before (PrintToolVersionTask) can be moved into the buildSrc/src/main/groovy/com/baeldung/PrintToolVersionTask.groovy. We have to only add some imports from Gradle API into a moved class.

我们之前定义的任务类型(PrintToolVersionTask)可以被移到buildSrc/src/main/groovy/com/baeldung/PrintToolVersionTask.groovy。我们只需将Gradle API的一些imports添加到移动的类中.

We can define an unlimited number of tasks types in the buildSrc folder. It’s easier to maintain, read, and the task type declaration isn’t in the same place as the task instantiation.

我们可以在buildSrc文件夹中定义无限数量的任务类型。这更容易维护、阅读,而且任务类型声明与任务实例化不在同一个地方。

We can use these types the same way we’re using types defined directly in the build script. We have to remember only to add appropriate imports.

我们可以像使用直接在构建脚本中定义的类型一样来使用这些类型。我们只需要记住添加适当的导入。

6. Define Task Type in the Plugin

6.在插件中定义任务类型

We can define a custom task types inside a custom Gradle plugin. Please refer to this article, which describes how to define a custom Gradle plugin, defined in the:

我们可以在一个自定义Gradle插件中定义一个自定义任务类型。请参考这篇文章,其中描述了如何定义一个自定义的Gradle插件,定义在:

  • build.gradle file
  • buildSrc folder as other Groovy classes

These custom tasks will be available for our build when we define a dependency to this plugin. Please note that ad-hoc tasks are also available – not only custom task types.

当我们定义对该插件的依赖时,这些自定义任务将可用于我们的构建。请注意,临时任务也是可用的–不仅仅是自定义任务类型。

7. Conclusion

7.结论

In this tutorial, we covered how to create a custom task in Gradle. There are a lot of plugins available which you can use in your build.gradle file that will provide a lot of custom task types you need.

在本教程中,我们介绍了如何在Gradle中创建一个自定义任务。有很多可用的插件,你可以在你的build.gradle文件中使用,它们将提供很多你需要的自定义任务类型。

As always, code snippets are available over on Github.

像往常一样,代码片段可在Github上获得