Создание двоичных плагинов
Разрабатывайте автономные двоичные плагины с использованием Groovy или Java и упаковывайте их для распространения.
«Создание двоичных плагинов» — бесплатный урок Groovy & Gradle: JVM Automation and Build Engineering на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Groovy & Gradle: JVM Automation and Build Engineering, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Groovy & Gradle: JVM Automation and Build Engineering содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Binary Plugins?
Welcome! In this lesson, we'll dive into building binary plugins for Gradle. Unlike simpler script plugins, binary plugins are compiled code (Java or Groovy) that offer superior reusability and structure.
- Reusability: Easily share across many projects.
- Encapsulation: Keep your build logic clean and organized.
- Testability: Easier to unit test complex logic.
Setting Up Your Plugin Project
A binary plugin is typically developed in its own Gradle project. For local development, a common approach is to place your plugin source code within the buildSrc directory of your main project.
The standard structure looks like this:
rootProject/buildSrc/src/main/groovy/com/coddykit/plugins/MyPlugin.groovybuild.gradlebuild.gradle(for the consumer project)
The Plugin<Project> Interface
Every binary Gradle plugin must implement the org.gradle.api.Plugin interface, specifically Plugin<Project>. This interface defines a single method: apply(Project project).
The Project object passed to apply is the project the plugin is being applied to. This is your entry point to configure that project.
package com.coddykit.plugins
import org.gradle.api.Plugin
import org.gradle.api.Project
class MyFirstPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
// Plugin logic goes here
// You can add tasks, extensions, etc.
}
}Plugin's Core: apply Method
The apply method is where your plugin's magic happens. Inside this method, you can perform various actions to configure the target project, such as:
- Creating custom tasks.
- Adding new configurations.
- Registering extensions for user configuration.
- Applying other plugins.
This method runs when Gradle applies your plugin to a project.
Adding a Simple Task
Let's create a basic plugin that adds a custom task named helloGradle to any project it's applied to. This task will simply print a greeting message.
We'll put this class in buildSrc/src/main/groovy/com/coddykit/plugins/GreetingPlugin.groovy.
package com.coddykit.plugins
import org.gradle.api.Plugin
import org.gradle.api.Project
class GreetingPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
project.tasks.create('helloGradle') {
doLast {
println "Hello from CoddyKit's Greeting Plugin!"
}
}
}
}Declaring Your Plugin ID
To make your plugin discoverable, you need to declare a unique ID for it in the plugin project's build.gradle file. This maps your plugin class to an ID that consumer projects will use.
This example build.gradle would be placed in buildSrc/build.gradle.
plugins {
id 'java-gradle-plugin' // Enables Gradle plugin development features
id 'groovy' // If your plugin is written in Groovy
}
repositories {
mavenCentral()
}
dependencies {
implementation gradleApi() // Provides Gradle API classes
implementation localGroovy() // Provides Groovy classes
}
gradlePlugin {
plugins {
greetingPlugin {
id = 'com.coddykit.greeting'
implementationClass = 'com.coddykit.plugins.GreetingPlugin'
}
}
}
// To build this plugin: gradle build (from buildSrc dir)Using Your Custom Plugin
Now that our GreetingPlugin is defined and has an ID, we can apply it to a consumer project. If the plugin is in buildSrc, it's automatically available to the root project.
Add this to your root project's build.gradle file:
plugins {
id 'com.coddykit.greeting' // Apply our custom plugin by ID
}
// To run the task:
// 1. Ensure GreetingPlugin is in buildSrc
// 2. Open terminal in your project's root
// 3. Run: gradle helloGradlePlugin Extensions for Configuration
For powerful and flexible plugins, you'll want to allow users to configure them. Gradle extensions are objects that plugins add to a project, providing a DSL (Domain Specific Language) for configuration.
You define an extension class with properties, then register it in your plugin's apply method. Users can then configure these properties in their build.gradle.
Plugin with Configuration
Here's an example of a plugin that uses an extension. First, the extension class (CoddyKitExtension.groovy) defines configurable properties. Then, the plugin (ConfigurablePlugin.groovy) creates an instance of this extension and registers it with the project, also creating a task that uses the configured message.
// src/main/groovy/com/coddykit/plugins/CoddyKitExtension.groovy
package com.coddykit.plugins
class CoddyKitExtension {
String message = "Default CoddyKit message"
}
// src/main/groovy/com/coddykit/plugins/ConfigurablePlugin.groovy
package com.coddykit.plugins
import org.gradle.api.Plugin
import org.gradle.api.Project
class ConfigurablePlugin implements Plugin<Project> {
@Override
void apply(Project project) {
// Create and register the extension
def extension = project.extensions.create('coddyKit', CoddyKitExtension)
project.tasks.create('displayConfigMessage') {
doLast {
println "CoddyKit Plugin says: ${extension.message}"
}
}
}
}Binary Plugin Check
Which of the following are key benefits of using a binary Gradle plugin compared to a simple script plugin?
Recap: Building Binary Plugins
Great job! You've learned the fundamentals of building binary Gradle plugins:
- Binary plugins offer reusability, encapsulation, and testability for your build logic.
- They implement the
Plugin<Project>interface, with core logic in theapplymethod. - You declare a unique plugin ID in your plugin project's
build.gradle. - Extensions provide a way for users to configure your plugin.
Next, we'll explore how to apply and publish these powerful plugins!
Часто задаваемые вопросы
Урок «Создание двоичных плагинов» бесплатный?
Да — полный текст урока «Создание двоичных плагинов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Groovy & Gradle: JVM Automation and Build Engineering, подпишись на CoddyKit PRO. Курс Groovy & Gradle: JVM Automation and Build Engineering содержит 4 уроков всего.
Чему я научусь в уроке «Создание двоичных плагинов»?
Разрабатывайте автономные двоичные плагины с использованием Groovy или Java и упаковывайте их для распространения. Ты практикуешь Groovy & Gradle: JVM Automation and Build Engineering с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Groovy & Gradle: JVM Automation and Build Engineering?
Предыдущий опыт не требуется. Groovy & Gradle: JVM Automation and Build Engineering на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Создание двоичных плагинов»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Groovy & Gradle: JVM Automation and Build Engineering?
Да. Каждый урок Groovy & Gradle: JVM Automation and Build Engineering включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Изучение плагинов Gradle
- Создание двоичных плагинов
- Применение и публикация плагинов
- Расширения плагинов и настраиваемые DSL