0Pricing
Groovy & Gradle: JVM Automation and Build Engineering · Урок

Свойства и настройка задач

Научитесь добавлять свойства к пользовательским задачам, настраивать их и обеспечивать инкрементальные сборки.

«Свойства и настройка задач» — бесплатный урок Groovy & Gradle: JVM Automation and Build Engineering на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Groovy & Gradle: JVM Automation and Build Engineering, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Groovy & Gradle: JVM Automation and Build Engineering содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What are Task Properties?

Custom Gradle tasks can be made highly flexible by adding properties. These properties act like variables that allow you to configure a task's behavior from your build.gradle script.

Using properties makes your custom tasks reusable and adaptable to different project needs without having to change their core logic.

Defining Simple Properties

To add a property to a custom task, you simply declare a public field within your task class. For basic types like String, int, or boolean, this is straightforward.

For more advanced scenarios, Gradle also offers dedicated Property types, but we'll start with simple declarations.

Custom Task with a Property

Here's a basic custom task defined directly in build.gradle. It has a message property that will be printed when the task runs. Notice the default value set for the property.

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction

class MyMessageTask extends DefaultTask {
    String message = "Default task message"

    @TaskAction
    void printMessage() {
        println "Task says: ${message}"
    }
}

task helloWorld(type: MyMessageTask)

Configuring Task Properties

Once a task property is defined, you can easily set its value from your build.gradle file. This is done within the task's configuration block, which allows you to customize the task instance.

Run the example to see how the default message is overridden.

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction

class MyMessageTask extends DefaultTask {
    String message = "Default task message"

    @TaskAction
    void printMessage() {
        println "Task says: ${message}"
    }
}

task helloWorld(type: MyMessageTask) {
    message = "Hello from CoddyKit!"
}

Inputs for Incremental Builds

One of Gradle's most powerful features is incremental builds. This means Gradle can skip tasks if their inputs and outputs haven't changed since the last build, saving a lot of time.

To enable this, you must tell Gradle which properties are considered task inputs. These are properties whose values influence the task's outcome.

Declaring Input Properties

You mark a property as an input using the @Input annotation. Gradle will then track its value. If the value changes between builds, the task will execute. If not, Gradle can mark it as UP-TO-DATE and skip it.

For file or directory inputs, use @InputFile, @InputDirectory, or @InputFiles.

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction

class MyInputTask extends DefaultTask {
    @Input
    String greeting = "Hola!"

    @TaskAction
    void greet() {
        println "Greeting: ${greeting}"
    }
}

task sayHello(type: MyInputTask) {
    greeting = "Bonjour!"
}

Outputs for Incremental Builds

Equally important are outputs. These are the files or directories that your task creates or modifies during its execution. Gradle also tracks these to determine if a task is up-to-date.

If a task's inputs haven't changed AND its declared outputs are present and valid, Gradle knows the task doesn't need to run again.

Declaring Output Properties

You use annotations like @OutputFile for a single result file or @OutputDirectory for a directory containing results. These tell Gradle where the task's generated artifacts will be stored.

The task will ensure the parent directory exists before writing the file.

import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction

class MyOutputFileTask extends DefaultTask {
    @Input
    String content = "Default report content."

    @OutputFile
    File outputFile = project.file("build/reports/output.txt")

    @TaskAction
    void generateFile() {
        outputFile.parentFile.mkdirs()
        outputFile.write(content)
        println "Generated: ${outputFile.name}"
    }
}

task generateReport(type: MyOutputFileTask) {
    content = "Report data for: " + new Date().format("yyyy-MM-dd HH:mm:ss")
}

The Power of Incremental Builds

By correctly declaring both inputs and outputs, you unlock Gradle's powerful incremental build feature. This means your tasks only run when necessary, drastically speeding up build times.

This optimization is crucial for efficient development workflows and robust CI/CD pipelines, ensuring quick feedback and resource savings.

Quick Check on Properties

Imagine you have a custom Gradle task that takes a specific configuration file as an input. Which annotation would you use for the property that defines the path to this single configuration file?

Recap: Task Properties & Incremental Builds

In this lesson, you learned how to add properties to custom tasks, making them configurable and reusable. You also discovered how to mark properties as inputs (e.g., @Input, @InputFile) and outputs (e.g., @OutputFile, @OutputDirectory).

These annotations are key to enabling Gradle's powerful incremental build feature, which significantly speeds up your builds by skipping tasks that are already up-to-date. Keep practicing to master efficient task configuration!

Часто задаваемые вопросы

Урок «Свойства и настройка задач» бесплатный?

Да — полный текст урока «Свойства и настройка задач» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Groovy & Gradle: JVM Automation and Build Engineering, подпишись на CoddyKit PRO. Курс Groovy & Gradle: JVM Automation and Build Engineering содержит 4 уроков всего.

Чему я научусь в уроке «Свойства и настройка задач»?

Научитесь добавлять свойства к пользовательским задачам, настраивать их и обеспечивать инкрементальные сборки. Ты практикуешь Groovy & Gradle: JVM Automation and Build Engineering с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Groovy & Gradle: JVM Automation and Build Engineering?

Предыдущий опыт не требуется. Groovy & Gradle: JVM Automation and Build Engineering на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Свойства и настройка задач»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Groovy & Gradle: JVM Automation and Build Engineering?

Да. Каждый урок Groovy & Gradle: JVM Automation and Build Engineering включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Определение пользовательских задач
  2. Типы и действия задач
  3. Свойства и настройка задач
  4. Инкрементальные задачи и проверки актуальности
← Назад к Groovy & Gradle: JVM Automation and Build Engineering