Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท Plugins

Writing Custom Gradle Plugins and Convention Plugins

Learn to write Gradle plugins: script plugins, buildSrc, precompiled convention plugins, binary plugins in Kotlin, extensions, task registration and testing them.

Once a few of your builds look alike, copying the same blocks between build.gradle.kts files becomes painful. Gradle's answer is to move shared logic into your own plugins. You can start tiny, with a few lines in a precompiled script, and grow into a published binary plugin later.

This lesson covers the three common homes for custom build logic: buildSrc, an included build-logic build with convention plugins, and a standalone binary plugin with an extension and a task. It builds on what plugins are.

Gradle cannot run on this website, so the Kotlin and Groovy files are read-only. Java stand-ins at the end show the same structure (plugin, extension, task) and run on the site.

Option 1: script plugins (simple, but limited)

A script plugin is a plain .gradle.kts file applied with apply(from = "gradle/quality.gradle.kts"). It works for tiny things, but it has no type-safe accessors, no tests and no IDE help. Prefer the options below.

Option 2: buildSrc

A directory named buildSrc next to settings.gradle.kts is built automatically before everything else, and its classes are on the classpath of all build scripts.

TEXT
my-project/
  settings.gradle.kts
  build.gradle.kts
  buildSrc/
    build.gradle.kts
    src/main/kotlin/
      java-conventions.gradle.kts
Kotlin
// buildSrc/build.gradle.kts
plugins {
    `kotlin-dsl`
}

repositories {
    mavenCentral()
}
Kotlin
// buildSrc/src/main/kotlin/java-conventions.gradle.kts
plugins {
    `java-library`
}

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

repositories { mavenCentral() }

tasks.withType<Test> {
    useJUnitPlatform()
    testLogging { events("failed", "skipped") }
}

The file name becomes the plugin ID. Any project can now write plugins { id("java-conventions") } and receive the toolchain, repository and test settings. This is a precompiled script plugin, the easiest way to share conventions.

The drawback: any change in buildSrc invalidates the build script classpath, so every project is reconfigured and caches suffer. That is why larger builds use an included build instead.

Option 3: an included build named build-logic

Same files, but in a separate build:

TEXT
settings.gradle.kts
build-logic/
  settings.gradle.kts
  conventions/
    build.gradle.kts
    src/main/kotlin/java-conventions.gradle.kts
Kotlin
// settings.gradle.kts (root)
pluginManagement {
    includeBuild("build-logic")
}

Now id("java-conventions") resolves from build-logic. Changing a convention only rebuilds the plugin and affected projects, and builds stay cacheable. See composite builds for the general mechanism.

A good layout uses several small convention plugins instead of one big one: java-conventions, publishing-conventions, spring-conventions. Each project then composes what it needs, a pattern known as convention plugins.

Option 4: a binary plugin with extension and task

A binary plugin is a class that implements Plugin<Project>. Here is one that adds a greeting {} extension and a greet task.

Kotlin
// build-logic/conventions/src/main/kotlin/GreetingPlugin.kt
import org.gradle.api.DefaultTask
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction

interface GreetingExtension {
    val message: Property<String>
}

abstract class GreetTask : DefaultTask() {
    @get:Input
    abstract val message: Property<String>

    @TaskAction
    fun greet() {
        println(message.get())
    }
}

class GreetingPlugin : Plugin<Project> {
    override fun apply(project: Project) {
        val ext = project.extensions.create("greeting", GreetingExtension::class.java)
        ext.message.convention("Hello from Gradle")
        project.tasks.register("greet", GreetTask::class.java) {
            group = "demo"
            message.set(ext.message)
        }
    }
}

Register it with a plugin ID in the build.gradle.kts of the plugin project:

Kotlin
plugins { `java-gradle-plugin` }

gradlePlugin {
    plugins {
        create("greeting") {
            id = "com.example.greeting"
            implementationClass = "GreetingPlugin"
        }
    }
}

Users then write:

Kotlin
plugins { id("com.example.greeting") }

greeting { message = "Hi, team" }

Key points of the example:

  • Property<String> is a lazy value: it is only read when the task runs, so users can set it after the plugin is applied.
  • convention(...) supplies a default that users may override.
  • register creates the task lazily; never use eager create in new code.
  • @Input declares what affects the result; Gradle uses it for up-to-date checks.
  • Abstract property getters are implemented by Gradle at runtime, which is why the task class is abstract.

Testing a plugin

The java-gradle-plugin adds GradleRunner (via gradleTestKit()), which runs a real build in a temp directory and lets you assert on output:

Kotlin
// in src/test/kotlin
val result = GradleRunner.create()
    .withProjectDir(tempDir)
    .withArguments("greet")
    .withPluginClasspath()
    .build()
assertTrue(result.output.contains("Hello from Gradle"))

Stand-in: plugin, extension and lazy task in Java

This model mirrors the structure above: an extension with a default, a task that reads the value late, and a plugin wiring them. Changing the extension after applying still affects the task, because the value is read lazily.

Java Stand-in: plugin + extension + lazy value (not Gradle)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Which option should I choose?

Where to put build logic

Script plugin One-off, no tests
buildSrc Quick start, small builds
build-logic Best for big builds
Published plugin Share across repos
1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What becomes the plugin ID of a precompiled script plugin file java-conventions.gradle.kts?

    For precompiled script plugins the file name without the .gradle.kts suffix is the plugin ID.
  2. 2. Why do large builds prefer an included build-logic over buildSrc?

    Any edit in buildSrc forces every project to be reconfigured and hurts caching, while an included build is better isolated.
  3. 3. What is the benefit of Property<String> in an extension?

    Providers and properties defer reading, so wiring tasks to extension values works regardless of configuration order.
  4. 4. Which API registers a task lazily?

    tasks.register creates the task only when it is needed, which keeps configuration fast. tasks.create builds it immediately.

Summary

  • Share build logic with convention plugins: precompiled scripts in buildSrc or, better, an included build-logic build.
  • A binary plugin implements Plugin<Project>, creates an extension and registers tasks.
  • Use lazy Property/Provider types and tasks.register.
  • Test plugins with Gradle TestKit.

Next: Settings, subprojects and project paths