Step-by-step instructions
These instructions follow on from what was achieved in the previous lesson.
Add a convention plugin
-
create a buildSrc directory
-
in there add a build.gradle.kts build script
-
add a single plugin
plugins { `kotlin-dsl` }
-
configure repositories to include Gradle Plugin Portal
repositories { gradlePluginPortal() }
-
in buildSrc add src/main/kotlin directory
-
add convention plugin script com.tomgregory.maxirail.common-conventions.gradle.kts
plugins { java } repositories { mavenCentral() } testing { suites { named("test", JvmTestSuite::class) { useJUnitJupiter() } } }
-
in IntelliJ IDEA’s Gradle Tool Window click Reload All Gradle Projects for IntelliJ IDEA to validate this file
-
in app’s build script apply the convention plugin by id
id("com.tomgregory.maxirail.common-conventions")
-
remove old build script configuration which was extracted into the convention plugin (i.e. java plugin, repositories, and testing blocks)
-
repeat for service subproject, but leave the java-library plugin
-
repeat for model subproject, but leave the java-library plugin
-
run
./gradlew cleanTest
test to ensure tests are still passing
Add a version catalog
-
under gradle directory create file libs.versions.toml
-
define Spring Boot version using TOML syntax
[versions] spring-boot = "2.6.4"
-
define 3 x Spring Boot dependencies, referencing version defined above
[libraries] spring-boot-web = { module = "org.springframework.boot:spring-boot-starter-web", version.ref = "spring-boot" } spring-boot-test = { module = "org.springframework.boot:spring-boot-starter-test", version.ref = "spring-boot" } spring-boot-starter = { module = "org.springframework.boot:spring-boot-starter", version.ref = "spring-boot" }
-
define Spring Boot plugin, referencing version defined above
[plugins] spring-boot = { id = "org.springframework.boot", version.ref = "spring-boot" }
-
in IntelliJ IDEA’s Gradle Tool Window click Reload All Gradle Projects to make this information available to build scripts
-
in the build script for app, update dependencies by using the type-safe accessor
dependencies { implementation(project(":service")) implementation(libs.spring.boot.web) testImplementation(libs.spring.boot.test) }
-
reference the Spring Boot plugin using the alias defined in the version catalog (IntelliJ IDEA may incorrectly show an error in the editor)
alias(libs.plugins.spring.boot)
-
in service’s build script use the type-safe accessor to reference spring-boot-starter
dependencies { api(project(":model")) implementation(libs.spring.boot.starter) }
-
run tests again with
./gradlew test
and see that everything is still working
Great! You just used the latest Gradle features to share build logic between multiple subprojects and improve maintainability.
GitHub repository
The gradle-multi-project-masterclass repository contains the final code solution for lessons 2-5.