Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 36 ยท Projects and Practice

Project: Build a Multi-module Java Application with Gradle

A hands-on Gradle project: build a three-module Java application with a convention plugin, version catalog, tests, coverage and a distribution, plus a runnable model of the app logic.

In this project you will set up a small but realistic Gradle build: a library with business logic, a CLI application that uses it, a shared convention plugin and a version catalog. It brings together settings, project dependencies, plugins, testing and distributions from the previous chapters.

The app is a tiny "shopping cart pricer". Because Gradle cannot run on this website, the Gradle files are shown read-only and you build them on your own machine, while the Java logic of every module runs here in the stand-ins so you can try the code itself.

To follow along locally, install a JDK (21 or newer) and Gradle once, run gradle init or create the files below, then use the wrapper (./gradlew).

Target layout

TEXT
shop/
  settings.gradle.kts
  gradle/libs.versions.toml
  build-logic/
    settings.gradle.kts
    conventions/
      build.gradle.kts
      src/main/kotlin/shop.java-conventions.gradle.kts
  pricing/                       (library)
    build.gradle.kts
    src/main/java/shop/pricing/Price.java
    src/main/java/shop/pricing/Cart.java
    src/test/java/shop/pricing/CartTest.java
  cli/                           (application)
    build.gradle.kts
    src/main/java/shop/cli/Main.java
flowchart LR
    BL["build-logic<br/>shop.java-conventions"] -.applies.-> P[":pricing"]
    BL -.applies.-> C[":cli"]
    C --> P

cli depends on pricing; both apply the convention plugin from build-logic.

Step 1: settings and catalog

Kotlin
// settings.gradle.kts
pluginManagement {
    includeBuild("build-logic")
}

rootProject.name = "shop"

include("pricing", "cli")
TOML
# gradle/libs.versions.toml
[versions]
junit = "5.11.4"

[libraries]
junit-bom = { module = "org.junit:junit-bom", version.ref = "junit" }
junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" }

Step 2: the convention plugin

Kotlin
// build-logic/settings.gradle.kts
dependencyResolutionManagement {
    repositories { mavenCentral() }
    versionCatalogs {
        create("libs") { from(files("../gradle/libs.versions.toml")) }
    }
}
rootProject.name = "build-logic"
include("conventions")
Kotlin
// build-logic/conventions/build.gradle.kts
plugins { `kotlin-dsl` }
Kotlin
// build-logic/conventions/src/main/kotlin/shop.java-conventions.gradle.kts
plugins {
    `java-library`
    jacoco
}

repositories { mavenCentral() }

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

val libs = versionCatalogs.named("libs")

dependencies {
    testImplementation(platform(libs.findLibrary("junit-bom").get()))
    testImplementation(libs.findLibrary("junit-jupiter").get())
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test {
    useJUnitPlatform()
    finalizedBy(tasks.jacocoTestReport)
}

(Accessing the catalog from precompiled script plugins needs this versionCatalogs lookup, because type-safe accessors are not generated there.)

Step 3: the library

Kotlin
// pricing/build.gradle.kts
plugins { id("shop.java-conventions") }
Java
// pricing/src/main/java/shop/pricing/Price.java
package shop.pricing;

public record Price(long cents) {
    public Price {
        if (cents < 0) throw new IllegalArgumentException("negative price");
    }
    public Price plus(Price other) { return new Price(cents + other.cents); }
    public Price times(int n) { return new Price(cents * n); }
    public Price withTax(int percent) { return new Price(cents + Math.round(cents * percent / 100.0)); }
    @Override public String toString() { return String.format("$%d.%02d", cents / 100, cents % 100); }
}
Java
// pricing/src/main/java/shop/pricing/Cart.java
package shop.pricing;

import java.util.*;

public class Cart {
    private final Map<String, Price> prices = new LinkedHashMap<>();
    private final Map<String, Integer> quantities = new LinkedHashMap<>();

    public void add(String item, Price unit, int qty) {
        prices.put(item, unit);
        quantities.merge(item, qty, Integer::sum);
    }

    public Price subtotal() {
        Price sum = new Price(0);
        for (var e : quantities.entrySet()) sum = sum.plus(prices.get(e.getKey()).times(e.getValue()));
        return sum;
    }
}

Here is the same logic as a single runnable file. You can edit it and run it here.

Java The pricing library logic (runs on the site)

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.

Step 4: a test

Java
// pricing/src/test/java/shop/pricing/CartTest.java
package shop.pricing;

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

class CartTest {
    @Test
    void sumsQuantities() {
        Cart cart = new Cart();
        cart.add("pen", new Price(150), 2);
        cart.add("pen", new Price(150), 1);
        assertEquals(new Price(450), cart.subtotal());
    }
}

Run ./gradlew :pricing:test, then open pricing/build/reports/tests/test/index.html and pricing/build/reports/jacoco/test/html/index.html.

Step 5: the CLI application

Kotlin
// cli/build.gradle.kts
plugins {
    id("shop.java-conventions")
    application
}

dependencies {
    implementation(project(":pricing"))
}

application {
    mainClass = "shop.cli.Main"
}
Java
// cli/src/main/java/shop/cli/Main.java
package shop.cli;

import shop.pricing.*;

public class Main {
    public static void main(String[] args) {
        Cart cart = new Cart();
        for (String arg : args) {
            String[] p = arg.split(":");               // name:cents:qty
            cart.add(p[0], new Price(Long.parseLong(p[1])), Integer.parseInt(p[2]));
        }
        System.out.println("Total with tax: " + cart.subtotal().withTax(20));
    }
}

Run it with ./gradlew :cli:run --args="pen:150:4 notebook:499:2".

This stand-in parses the same argument format so you can try different inputs by editing the array:

Java The CLI argument parsing (runs on the site)

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.

Step 6: build and package

TEXT
./gradlew build                 # compile, test, jars, coverage report
./gradlew :cli:installDist      # build/install/cli/bin/cli
./gradlew :cli:distZip          # build/distributions/cli-<version>.zip
./gradlew build --scan          # optional: where did the time go?

Check: the second ./gradlew build should show UP-TO-DATE for almost every task (incremental builds).

Stretch goals

  1. Add java-test-fixtures to pricing and share a CartBuilder with cli tests.
  2. Add an integrationTest suite to cli that runs the installed script (test suites).
  3. Publish pricing to build/repo with maven-publish (publishing).
  4. Enforce 80% line coverage with jacocoTestCoverageVerification.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why does the cli project use implementation(project(":pricing"))?

    A project dependency uses the other project's output and makes Gradle build it before compiling cli.
  2. 2. Where do the shared Java version, repositories and JUnit setup live in this project?

    A convention plugin keeps the shared configuration in one place and each project applies it explicitly.
  3. 3. What does ./gradlew :cli:installDist produce?

    installDist writes the distribution layout to build/install/<name>, so you can run the script locally.

Summary

  • A multi-module build combines settings, a catalog, a convention plugin, project dependencies and plugins.
  • The library holds logic and tests; the CLI depends on it with project(":pricing").
  • installDist and distZip package the application.
  • A second build should be almost entirely UP-TO-DATE.

Next: Project: a custom plugin with a task and tests