Search

Dark theme | Light theme

February 17, 2021

Gradle Goodness: Setting Plugin Version From Property In Plugins Section

The plugins section in our Gradle build files can be used to define Gradle plugins we want to use. Gradle can optimize the build process if we use plugins {...} in our build scripts, so it is a good idea to use it. But there is a restriction if we want to define a version for a plugin inside the plugins section: the version is a fixed string value. We cannot use a property to set the version inside the plugins section. We can overcome this by using a pluginsManagement section in a settings file in the root of our project. Inside the pluginsManagement section we can use properties to set the version of a plugin we want to use. Once it is defined inside pluginsManagement we can use it in our project build script without having the specify the version. This allows us to have one place where all plugin versions are defined. We can even use a gradle.properties file in our project with all plugin versions and use that in pluginsManagement.

In the following settings file we use pluginsManagement to use a project property springBootPluginVersion to set the version to use for the Spring Boot Gradle plugin.

// File: settings.gradle.kts
pluginManagement {
    val springBootPluginVersion: String by settings // use project property with version
    plugins {
        id("org.springframework.boot") version "${springBootPluginVersion}"
    }
}

Next in our project build file we can simply reference the id of the Spring Boot Gradle plugin without the version. The version is already resolved in our settings file:

// File: build.gradle.kts
plugins {
    java
    application
    id("org.springframework.boot") // no version here: it is set in settings.gradle.kts
}

application {
    mainClass.set("com.mrhaki.sample.App")
}

Finally we can add a gradle.properties file with the project property (or specify it on the command line or environment variable):

# File: gradle.properties
springBootPluginVersion=2.4.2

Written with Gradle 6.8.2.