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 Convention Plugins?

In large Gradle multi-project builds, maintaining consistent configurations across many subprojects can become a challenge. This is where Convention Plugins come in handy.

A convention plugin is essentially a way to package and reuse common build logic and configurations specific to your organization or project. They help enforce standards and reduce boilerplate.

The Problem: Inconsistent Build Logic

Imagine you have several Java subprojects. Each needs to apply the java-library plugin, set a specific Java toolchain, and configure common repositories. Without convention plugins, you might end up with repetitive and slightly different configurations in each build.gradle file.

/* project-a/build.gradle */
plugins {
    id 'java-library'
}
java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}
repositories {
    mavenCentral()
}

/* project-b/build.gradle */
plugins {
    id 'java-library'
}
java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}
repositories {
    mavenCentral()
}

Centralizing Build Logic with `buildSrc`

To solve the problem of repetition, Gradle offers a special directory: buildSrc. When present in your project root, Gradle automatically compiles any code (Groovy, Kotlin, Java) found within buildSrc and adds it to the classpath of your build scripts.

This makes buildSrc the perfect place to define internal build logic, custom tasks, and especially, convention plugins.

Crafting Your First Convention Plugin

Let's create a simple convention plugin to standardize our Java library setup. We'll define it in buildSrc/src/main/groovy/my.java-conventions.groovy. This plugin will apply the java-library plugin, set Java 17 as the toolchain, and add mavenCentral().

// buildSrc/src/main/groovy/my.java-conventions.groovy
plugins {
    id 'java-library'
}

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

repositories {
    mavenCentral()
}

Applying Your Convention Plugin

Once you've defined your convention plugin in buildSrc, you can apply it to any subproject's build.gradle file using its ID. Notice how much cleaner and more concise the subproject's build file becomes!

// subproject-a/build.gradle
plugins {
    id 'my.java-conventions'
}

// All Java library, Java 17, and Maven Central settings
// are now applied automatically by the convention plugin!

Expanding Conventions: Dependencies & Tests

Convention plugins can do much more than just basic settings. You can enforce common dependencies, configure testing frameworks, or standardize other build aspects. Here, we add JUnit Jupiter dependencies and a common test logging configuration.

// buildSrc/src/main/groovy/my.java-conventions.groovy (updated)
plugins {
    id 'java-library'
}
// ... (previous Java toolchain and repositories config)

dependencies {
    testImplementation platform('org.junit:junit-bom:5.10.0')
    testImplementation 'org.junit.jupiter:junit-jupiter'
}

test {
    useJUnitPlatform()
    testLogging {
        events "passed", "skipped", "failed"
    }
}

Convention Plugins with Kotlin DSL

Just like regular build scripts, convention plugins can also be written using the Kotlin DSL (.gradle.kts files). This provides compile-time safety and better IDE support, which can be very valuable for complex build logic.

The structure remains similar, just with Kotlin syntax.

// buildSrc/src/main/kotlin/my.kotlin-conventions.gradle.kts
plugins {
    java
}

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
}

repositories {
    mavenCentral()
}

Applying to the Root Project

While convention plugins are often used for subprojects, they can also be applied to the root project's build.gradle. This is useful for defining build-wide properties or configurations that should apply to the entire project, like common dependency versions.

// build.gradle (root project)
plugins {
    id 'my.root-conventions'
}

// buildSrc/src/main/groovy/my.root-conventions.groovy
ext {
    // Define properties accessible throughout the build
    springBootVersion = '3.2.0'
    kotlinVersion = '1.9.0'
}

Benefits and Best Practices

Convention plugins are a cornerstone of maintainable, large-scale Gradle builds:

  • Consistency: Ensures all projects adhere to organizational standards.
  • Reduced Duplication: Centralizes common build logic, eliminating copy-pasting.
  • Easier Maintenance: Update standards in one place; all projects instantly benefit.
  • Improved Readability: Subproject build files become shorter and more focused on project-specific details.

When creating them, keep plugins focused on a single concern, use clear IDs, and leverage Kotlin DSL for type safety.

Convention Checkpoint

Convention plugins are a powerful way to standardize build logic and enforce organizational standards. Let's test your understanding.

Recap: Mastering Convention Plugins

You've now learned about Gradle Convention Plugins! They are an essential tool for managing complex, multi-project builds.

  • Convention plugins centralize common build logic.
  • They are typically defined in the buildSrc directory.
  • They help enforce consistent configurations (Java versions, dependencies, test setups).
  • They drastically reduce boilerplate and improve maintainability.

By leveraging convention plugins, you can build more robust and scalable Gradle projects.

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

Урок «Плагины соглашений и логика сборки» бесплатный?

Да — полный текст урока «Плагины соглашений и логика сборки» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 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. Сканирование сборок Gradle и аналитика
  2. Безопасность и управление учётными данными
  3. Плагины соглашений и логика сборки
  4. Каталоги версий зависимостей и платформы
← Назад к Groovy & Gradle: JVM Automation and Build Engineering