Kotlin › Practice

Structuring Kotlin Spring multi-module builds with build-logic

Migrating a Kotlin Spring multi-module build from subprojects to Gradle build-logic convention plugins, with configuration and build cache timings.

Structuring Kotlin Spring multi-module builds with build-logic

Splitting a study project into four modules while sharing Gradle configuration through a root subprojects {} block caused bootJar failures and leaked Spring dependencies into the domain layer. Here is how I migrated the build to a build-logic included build and what I measured across configuration cache and build cache combinations.

Tested with Gradle 8.7 (Wrapper), Kotlin 1.9.23, Spring Boot 3.2.4, io.spring.dependency-management 1.1.4, and Java 17 (Temurin 17.0.16). All timings are wall-clock durations from ./gradlew --offline with a warm daemon on a local PC (12 cores, 32GB RAM, Windows with Docker Desktop/WSL2), dropping the first run and taking the median of 3–5 runs per scenario.

Background

When I first split the project into four modules (domain, application, infra, and api), I put the Kotlin, Spring, JPA, and Spring Boot plugins inside a root subprojects {} block. That kept each module’s build.gradle.kts down to a short dependencies {} block, so it looked clean at first glance.

1
2
3
4
5
6
7
8
9
10
11
12
// build.gradle.kts (root, original setup)
subprojects {
    apply(plugin = "org.jetbrains.kotlin.jvm")
    apply(plugin = "org.jetbrains.kotlin.plugin.spring")
    apply(plugin = "org.jetbrains.kotlin.plugin.jpa")
    apply(plugin = "org.springframework.boot")
    apply(plugin = "io.spring.dependency-management")

    dependencies {
        "testImplementation"("org.springframework.boot:spring-boot-starter-test")
    }
}

The flaw showed up immediately: every module received the exact same plugins regardless of its role. Running ./gradlew build failed on the application module because it has no main class to package into an executable JAR.

1
2
3
4
> Task :application:bootJar FAILED
Execution failed for task ':application:bootJar'.
> Error while evaluating property 'mainClass' of task ':application:bootJar'.
   > Main class name has not been configured and it could not be resolved from classpath build\classes\kotlin\main

You can disable bootJar on library modules one by one, but that turns the root script into a growing list of exceptions. What bothered me more was dependency leakage in domain, which I wanted to keep as pure Kotlin. Counting unique entries in ./gradlew :domain:dependencies --configuration testRuntimeClasspath returned 73 dependencies, pulling in the Spring test context, AssertJ, and Mockito. After moving the project to convention plugins, the same classpath dropped to 2 dependencies: kotlin-stdlib and JetBrains annotations.

How build-logic works under the hood

build-logic is an included build wired into the root project via pluginManagement { includeBuild("build-logic") } in settings.gradle.kts. When you apply the kotlin-dsl plugin inside build-logic, Gradle compiles files such as src/main/kotlin/club.spring-library.gradle.kts as precompiled script plugins. The filename without .gradle.kts becomes the plugin ID (club.spring-library). Under the hood, Gradle generates a Plugin<Project> implementation class and plugin descriptor for each script, so consumer modules resolve them just like binary plugins.

flowchart TD
    A["settings.gradle.kts"] -->|"includeBuild"| B["build-logic included build"]
    B --> C["kotlin-dsl compiles .gradle.kts"]
    C --> D["Generates Plugin class and ID"]
    D --> E["Modules opt in via plugins block"]
    E --> F["Each module gets only what it needs"]

The real shift is direction. With subprojects {}, the root project pushes configuration down into every child project. With convention plugins, each child module pulls only the conventions it declares in its plugins {} block. Enabling Gradle 8.7’s incubating Isolated Projects feature (-Dorg.gradle.unsafe.isolated-projects=true) makes this boundary obvious: the subprojects {} build failed with 40 problems (4 unique, including Cannot access project ':api' from project ':'), while the build-logic build passed without errors.

Project setup

Start by centralizing every plugin and library version in gradle/libs.versions.toml so the main build and build-logic read from the same catalog.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# gradle/libs.versions.toml
[versions]
kotlin = "1.9.23"
spring-boot = "3.2.4"
spring-dependency-management = "1.1.4"

[libraries]
kotlin-gradle-plugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" }
kotlin-allopen = { module = "org.jetbrains.kotlin:kotlin-allopen", version.ref = "kotlin" }
kotlin-noarg = { module = "org.jetbrains.kotlin:kotlin-noarg", version.ref = "kotlin" }
spring-boot-gradle-plugin = { module = "org.springframework.boot:spring-boot-gradle-plugin", version.ref = "spring-boot" }
spring-dependency-management-plugin = { module = "io.spring.gradle:dependency-management-plugin", version.ref = "spring-dependency-management" }
spring-boot-starter = { module = "org.springframework.boot:spring-boot-starter" }
spring-boot-starter-web = { module = "org.springframework.boot:spring-boot-starter-web" }
spring-boot-starter-data-jpa = { module = "org.springframework.boot:spring-boot-starter-data-jpa" }
spring-boot-starter-test = { module = "org.springframework.boot:spring-boot-starter-test" }
jackson-module-kotlin = { module = "com.fasterxml.jackson.module:jackson-module-kotlin" }
kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect" }
h2 = { module = "com.h2database:h2" }

Register build-logic in the root settings.gradle.kts and enforce centralized repository declarations.

1
2
3
4
5
6
7
8
9
10
11
12
// settings.gradle.kts
pluginManagement {
    includeBuild("build-logic")
}

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories { mavenCentral() }
}

rootProject.name = "club"
include("domain", "application", "infra", "api")

Next, point build-logic/settings.gradle.kts at the same libs.versions.toml file, and declare the plugin artifacts as implementation dependencies in build-logic/build.gradle.kts.

1
2
3
4
5
6
7
8
9
10
11
12
// build-logic/settings.gradle.kts
dependencyResolutionManagement {
    repositories {
        gradlePluginPortal()
        mavenCentral()
    }
    versionCatalogs {
        create("libs") { from(files("../gradle/libs.versions.toml")) }
    }
}

rootProject.name = "build-logic"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// build-logic/build.gradle.kts
plugins {
    `kotlin-dsl`
}

dependencies {
    implementation(libs.kotlin.gradle.plugin)
    implementation(libs.kotlin.allopen)
    implementation(libs.kotlin.noarg)
    implementation(libs.spring.boot.gradle.plugin)
    implementation(libs.spring.dependency.management.plugin)
    // Workaround for type-safe libs accessors inside precompiled scripts (gradle/gradle#15383)
    implementation(files(libs.javaClass.superclass.protectionDomain.codeSource.location))
}

I layered the conventions from base to executable: club.kotlin-common (JVM toolchain and JUnit 5) → club.spring-library (Spring Boot BOM and test starter) → club.spring-boot-app (Spring Boot packaging plugin).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// build-logic/src/main/kotlin/club.kotlin-common.gradle.kts
plugins {
    id("org.jetbrains.kotlin.jvm")
}

kotlin {
    jvmToolchain(17)
    compilerOptions {
        freeCompilerArgs.add("-Xjsr305=strict")
    }
}

tasks.withType<Test>().configureEach {
    useJUnitPlatform()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// build-logic/src/main/kotlin/club.spring-library.gradle.kts
import org.springframework.boot.gradle.plugin.SpringBootPlugin

plugins {
    id("club.kotlin-common")
    id("org.jetbrains.kotlin.plugin.spring")
    id("io.spring.dependency-management")
}

dependencyManagement {
    imports { mavenBom(SpringBootPlugin.BOM_COORDINATES) }
}

val libs = the<org.gradle.accessors.dm.LibrariesForLibs>()

dependencies {
    "testImplementation"(libs.spring.boot.starter.test)
}
1
2
3
4
5
// build-logic/src/main/kotlin/club.spring-boot-app.gradle.kts
plugins {
    id("club.spring-library")
    id("org.springframework.boot")
}

Only infra defines JPA entities, so the open class and no-arg constructor rules live in a dedicated club.jpa convention. If you want the details on why Kotlin JPA entities need those two compiler plugins, see my post on Kotlin JPA entity design with allopen and noarg.

1
2
3
4
5
6
7
8
9
10
11
// build-logic/src/main/kotlin/club.jpa.gradle.kts
plugins {
    id("club.spring-library")
    id("org.jetbrains.kotlin.plugin.jpa")
}

allOpen {
    annotation("jakarta.persistence.Entity")
    annotation("jakarta.persistence.MappedSuperclass")
    annotation("jakarta.persistence.Embeddable")
}

With the conventions in place, each module declares only its own role: domain applies club.kotlin-common, application applies club.spring-library, infra applies club.jpa, and api applies club.spring-boot-app.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// api/build.gradle.kts
plugins {
    id("club.spring-boot-app")
}

dependencies {
    implementation(project(":domain"))
    implementation(project(":application"))
    runtimeOnly(project(":infra")) // Prevent api code from importing JPA types directly
    implementation(libs.spring.boot.starter.web)
    implementation(libs.jackson.module.kotlin)
    implementation(libs.kotlin.reflect)
    runtimeOnly(libs.h2)
}
1
2
3
4
5
6
# api/src/main/resources/application.yml
spring:
  datasource:
    url: jdbc:h2:mem:club
  jpa:
    open-in-view: false

One small snag during the refactor: I originally placed @EnableJpaRepositories on the main application class in api. Because infra declares Spring Data JPA with implementation rather than api, those types aren’t visible on api’s compile classpath and compilation failed with Unresolved reference: EnableJpaRepositories. Moving JPA configuration into a @Configuration class inside infra fixed the build and let api keep infra as a runtimeOnly dependency.

Build time benchmarks

To see how much build speed actually changed, I measured ./gradlew build across five scenarios with and without Gradle’s configuration cache.

Scenario (build)Config cache offConfig cache on
Clean build, no build cache5,812ms (5,775–5,971)-
Clean build, build cache hit1,757ms (1,737–1,847)1,101ms (1,078–1,175)
No-op (no changes)1,202ms (1,166–1,306)766ms (764–784)
Non-ABI change in application5,693ms (5,166–7,108)4,615ms (4,480–4,694)
ABI change in domain5,662ms (5,538–6,377)4,892ms (4,864–5,575)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
  "type": "bar",
  "data": {
    "labels": ["Clean, no cache", "Clean, build cache", "No-op", "application non-ABI", "domain ABI"],
    "datasets": [
      { "label": "Config cache off (ms)", "data": [5812, 1757, 1202, 5693, 5662], "backgroundColor": "#7aa2f7" },
      { "label": "Config cache on (ms)", "data": [null, 1101, 766, 4615, 4892], "backgroundColor": "#9ece6a" }
    ]
  },
  "options": {
    "plugins": { "title": { "display": true, "text": "Median 4-module build duration (Gradle 8.7)" } },
    "scales": { "y": { "beginAtZero": true, "title": { "display": true, "text": "ms" } } }
  }
}

The build cache made the biggest difference. On a clean build, 8 tasks came back FROM-CACHE, cutting total time from 5.8s down to 1.8s. Turning on the configuration cache shaved another 0.4–1.1s off every run and skipped up-to-date checks for 9 build-logic tasks, reducing executed tasks from 29 to 19.

Incremental builds improved less than I expected. Even for a non-ABI change in application, both :application:test and :api:test (which boots @SpringBootTest) re-ran, accounting for most of the 4–5 seconds; an ABI change in domain only added recompilation of domain and infra on top of that. Running ./gradlew help was actually slightly slower with build-logic (840ms vs. 730ms) because Gradle checks the included build, though enabling the configuration cache closed the gap (694ms vs. 669ms). At four modules, the real payoff of convention plugins isn’t raw speed—it’s strict module boundaries and accurate configuration.

Decision matrix and caveats

SituationRecommended approach
2–3 modules with identical plugins and settingsKeep a single module or shared root settings
Modules with distinct roles (pure library, executable app, JPA)build-logic convention plugins
Sharing build rules across multiple repositoriesPublish convention plugins from a dedicated repo
Sharing dependency versions onlylibs.versions.toml version catalog

There are clear cases when not to use build-logic. In a single-module project, it only adds kotlin-dsl compilation time and included-build overhead for zero benefit. Even in multi-module repositories, splitting conventions into one-line micro-plugins makes it harder to trace where a setting came from than just reading a normal build script.

Precompiled script plugins don’t automatically generate type-safe libs accessors. The files(libs.javaClass.superclass.protectionDomain.codeSource.location) trick above is an unofficial workaround for Gradle issue #15383, so verify it whenever you upgrade Gradle. Likewise, Isolated Projects is still incubating in Gradle 8.7—I only enabled it as a compatibility check, not as a permanent default.

Checklist

  • Is org.springframework.boot applied only to executable modules so library modules don’t fail on bootJar?
  • Is the domain module’s testRuntimeClasspath free of Spring and JPA dependencies?
  • Are all versions managed in a single libs.versions.toml shared by both the main build and build-logic?
  • Are the build cache and configuration cache enabled in gradle.properties with an empty problem report?
  • Have all subprojects {} and allprojects {} blocks been removed from the root build script?
This post is licensed under CC BY 4.0 by the author.