SyntaxPilot
Courses/Java/Lesson 45
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Java · Lesson 45 of 51

Maven and Gradle, project structure

queued

These are the notes for Java episode 45. Ravi's chai app must send every bill to a delivery app as JSON, so we use a library, Gson. Adding its jar by hand breaks at run time (NoClassDefFoundError), and would break differently on every developer's laptop. So we invent a build tool: one file that names everything the project needs, a central library of jars, standard folders and standard commands. Then we use the two big ones: Maven and Gradle. Every command was really run (Apache Maven 3.9.11, Gradle 8.14.3, JDK 21). The recording machine had no internet, so "Maven Central" was a local mirror of it; that is why one error names central-mirror and dependency:tree prints some versions as debian. On your laptop you'll see central and real version numbers. Long outputs are shortened where you see ….

The problem: libraries by hand

Real-life example: Ravi's app joins a delivery app. The app wants each bill as JSON (a text format apps use to exchange data). Google's Gson library turns any Java object into JSON. A library is ready-made code shipped as a .jar file. And Ravi's nephew Arjun joins the project on his own laptop.

Bill.java:

import com.google.gson.Gson;

public class Bill {
    record Receipt(int cups, int total) {}

    static int total(int cups, int price) {
        int sum = cups * price;
        if (cups >= 10) sum = sum - sum / 10;
        return sum;
    }

    public static void main(String[] args) {
        Receipt r = new Receipt(12, total(12, 15));
        System.out.println(new Gson().toJson(r));
    }
}

We downloaded gson-2.10.1.jar into lib/ by hand:

$ ls -R
.:
Bill.java
lib

./lib:
gson-2.10.1.jar

Compile without it:

$ javac -d out Bill.java
Bill.java:1: error: package com.google.gson does not exist
import com.google.gson.Gson;
                      ^
Bill.java:14: error: cannot find symbol
        System.out.println(new Gson().toJson(r));
                               ^
  symbol:   class Gson
  location: class Bill
2 errors

Compile with it, but run without it:

$ javac -cp lib/gson-2.10.1.jar -d out Bill.java && java -cp out Bill
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/gson/Gson
    at Bill.main(Bill.java:14)
Caused by: java.lang.ClassNotFoundException: com.google.gson.Gson
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:526)
    ... 1 more

NoClassDefFoundError: Gson was on the compile classpath but not on the run classpath. They are two different things. With both:

$ java -cp out:lib/gson-2.10.1.jar Bill
{"cups":12,"total":162}

It works, on this laptop. Why this doesn't scale:

Problem What goes wrong
Jars downloaded by hand from where? which version? Arjun gets a different one
Libraries need other libraries JUnit alone needs several more jars (transitive dependencies)
Long commands, typed by hand everyone types them a little differently
Every project has its own folders nobody knows where anything is

The result: "but it works on my machine!" What we want: one file listing every dependency by name and version, a central repository the tool downloads from automatically, and standard folders and commands. That is a build tool.

Real-life example: Ravi's supply order. The order list (brand, item, pack size) is pom.xml with coordinates (groupId:artifactId:version); the wholesale market is Maven Central; Ravi's storeroom is your local repository ~/.m2/repository; the fixed opening routine is the lifecycle.

Maven

The standard layout

$ find . -type f | sort
./pom.xml
./src/main/java/in/syntaxpilot/chai/Bill.java
./src/test/java/in/syntaxpilot/chai/BillTest.java
Folder What goes there
pom.xml the build file
src/main/java the app's code (the package in.syntaxpilot.chai becomes folders)
src/main/resources non-code files for the app (config, text)
src/test/java the tests
target/ everything Maven builds (delete it any time: mvn clean)

This is convention over configuration: follow the standard layout and you configure almost nothing. Gradle uses the same folders.

pom.xml

POM = Project Object Model. The full file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>

  <groupId>in.syntaxpilot</groupId>
  <artifactId>chai-bill</artifactId>
  <version>1.0.0</version>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.10.1</version>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.10.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>   <!-- plugin versions pinned -->
      <plugin><artifactId>maven-clean-plugin</artifactId><version>3.2.0</version></plugin>
      <plugin><artifactId>maven-resources-plugin</artifactId><version>3.3.0</version></plugin>
      <plugin><artifactId>maven-compiler-plugin</artifactId><version>3.10.1</version></plugin>
      <plugin><artifactId>maven-surefire-plugin</artifactId><version>2.22.3</version></plugin>
      <plugin><artifactId>maven-jar-plugin</artifactId><version>3.3.0</version></plugin>
      <plugin><artifactId>maven-install-plugin</artifactId><version>3.1.1</version></plugin>
      <plugin><artifactId>maven-dependency-plugin</artifactId><version>3.5.0</version></plugin>
    </plugins>
  </build>
</project>
  • groupId (usually your domain backwards), artifactId (the project's name) and version are this project's coordinates.
  • maven.compiler.release 21: compile for Java 21.
  • Each <dependency> names a library by its coordinates. Gson has the default scope, compile: needed everywhere.
  • JUnit has scope test: only for compiling and running the tests; it never ships with the app.
  • The <build> section pins the plugin versions, so the build repeats exactly. (Maven has defaults for these, so small projects often leave them out.)
Scope Available to Example
compile (default) main code, tests, at run time Gson
test tests only JUnit
provided compile time; the server supplies it at run time Servlet API
runtime run time only, not to compile against a JDBC driver

mvn package

$ mvn -B package
[INFO] Building chai-bill 1.0.0
[INFO] --- resources:3.3.0:resources (default-resources) @ chai-bill ---
[INFO] --- compiler:3.10.1:compile (default-compile) @ chai-bill ---
[INFO] Compiling 1 source file to target/classes
[INFO] --- resources:3.3.0:testResources (default-testResources) @ chai-bill ---
[INFO] --- compiler:3.10.1:testCompile (default-testCompile) @ chai-bill ---
[INFO] Compiling 1 source file to target/test-classes
[INFO] --- surefire:2.22.3:test (default-test) @ chai-bill ---
[INFO] Running in.syntaxpilot.chai.BillTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.07 s - in in.syntaxpilot.chai.BillTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] --- jar:3.3.0:jar (default-jar) @ chai-bill ---
[INFO] Building jar: target/chai-bill-1.0.0.jar
[INFO] BUILD SUCCESS
…
$ ls target
chai-bill-1.0.0.jar
classes
generated-sources
generated-test-sources
maven-archiver
maven-status
surefire-reports
test-classes

Maven compiled the main code, compiled the tests, ran them with Surefire (Maven's test plugin), and packed the classes into target/chai-bill-1.0.0.jar.

The lifecycle

validate → compile → test → package → verify → install → deploy

Phase Does
validate checks the pom is correct
compile compiles src/main/java
test compiles and runs the tests
package makes the jar
verify extra checks (e.g. integration tests)
install copies the jar into your ~/.m2 so your other projects can use it
deploy uploads it to a shared repository for your team

Asking for a phase runs every phase before it, in order. mvn clean deletes target/; mvn clean package gives a fresh build. The work in each phase is done by plugins (compiler, surefire, jar).

The local repository and transitive dependencies

$ ls ~/.m2/repository/com/google/code/gson/gson/2.10.1/
_remote.repositories
gson-2.10.1.jar
gson-2.10.1.pom

Jars are downloaded once into ~/.m2/repository/<groupId as folders>/<artifactId>/<version>/ and reused by every project.

$ mvn -B dependency:tree
[INFO] Building chai-bill 1.0.0
[INFO] --- dependency:3.5.0:tree (default-cli) @ chai-bill ---
[INFO] in.syntaxpilot:chai-bill:jar:1.0.0
[INFO] +- com.google.code.gson:gson:jar:2.10.1:compile
[INFO] \- org.junit.jupiter:junit-jupiter:jar:5.10.1:test
[INFO]    +- org.junit.jupiter:junit-jupiter-api:jar:debian:test
[INFO]    |  +- org.opentest4j:opentest4j:jar:debian:test
[INFO]    |  \- org.junit.platform:junit-platform-commons:jar:1.9.1:test
[INFO]    +- org.junit.jupiter:junit-jupiter-params:jar:debian:test
[INFO]    |  \- com.univocity:univocity-parsers:jar:debian:test
[INFO]    +- org.junit.jupiter:junit-jupiter-engine:jar:debian:test
[INFO]    |  \- org.junit.platform:junit-platform-engine:jar:debian:test
[INFO]    \- org.apiguardian:apiguardian-api:jar:debian:test
[INFO] BUILD SUCCESS
…

Under junit-jupiter are jars we never asked for: the API, the engine, the params module, opentest4j, the platform. These are transitive dependencies: the dependencies of our dependencies, found and downloaded automatically.

A failing test stops the build

With a wrong test (assertEquals(150, Bill.total(10, 15))):

$ mvn -B package
[INFO] Building chai-bill 1.0.0
[INFO] --- resources:3.3.0:resources (default-resources) @ chai-bill ---
[INFO] --- compiler:3.10.1:compile (default-compile) @ chai-bill ---
[INFO] --- resources:3.3.0:testResources (default-testResources) @ chai-bill ---
[INFO] --- compiler:3.10.1:testCompile (default-testCompile) @ chai-bill ---
[INFO] Compiling 1 source file to target/test-classes
[INFO] --- surefire:2.22.3:test (default-test) @ chai-bill ---
[INFO] Running in.syntaxpilot.chai.BillTest
[ERROR] Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.111 s <<< FAILURE! - in in.syntaxpilot.chai.BillTest
[ERROR] tenCupsGetTenPercentOff  Time elapsed: 0.024 s  <<< FAILURE!
org.opentest4j.AssertionFailedError: expected: <150> but was: <135>
    at in.syntaxpilot.chai.BillTest.tenCupsGetTenPercentOff(BillTest.java:14)
[ERROR] Failures: 
[ERROR]   BillTest.tenCupsGetTenPercentOff:14 expected: <150> but was: <135>
[ERROR] Tests run: 2, Failures: 1, Errors: 0, Skipped: 0
[INFO] BUILD FAILURE
…

test comes before package, so no jar is made from code whose tests fail.

Gradle

Same src folders; the build is described in build.gradle (Groovy) or build.gradle.kts (Kotlin). settings.gradle names the project:

rootProject.name = 'chai-bill'

build.gradle:

plugins {
    id 'application'
}

group = 'in.syntaxpilot'
version = '1.0.0'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.google.code.gson:gson:2.10.1'
    testImplementation 'org.junit.jupiter:junit-jupiter:5.10.1'
}

application {
    mainClass = 'in.syntaxpilot.chai.Bill'
}

test {
    useJUnitPlatform()
}
  • application plugin: adds tasks to compile, test, package and run the app.
  • repositories { mavenCentral() }: the same central library as Maven.
  • implementation = needed by the app (like Maven's compile scope); testImplementation = tests only (like scope test).
  • useJUnitPlatform() tells Gradle to run JUnit 5 tests.

Gradle 9 note: Gradle 8 still loads the JUnit platform launcher automatically and prints a deprecation note (below). With Gradle 9 add this line to dependencies:

testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

(with a version, or with testImplementation platform('org.junit:junit-bom:<version>') to align all JUnit versions).

$ gradle build --console=plain
> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes
> Task :jar
> Task :startScripts
> Task :distTar
> Task :distZip
> Task :assemble
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :test
> Task :check
> Task :build
Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0.
BUILD SUCCESSFUL in 4s
7 actionable tasks: 7 executed
…

Gradle calls its steps tasks: compileJava, jar, compileTestJava, test, check, build.

$ gradle run --console=plain
> Task :compileJava UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :run
{"cups":12,"total":162}
BUILD SUCCESSFUL in 2s
2 actionable tasks: 1 executed, 1 up-to-date
…

UP-TO-DATE: nothing changed, so Gradle skipped the task. This is an incremental build.

$ gradle test --console=plain
> Task :compileJava UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :test FAILED
BillTest > tenCupsGetTenPercentOff() FAILED
    org.opentest4j.AssertionFailedError at BillTest.java:14
2 tests completed, 1 failed
* What went wrong:
Execution failed for task ':test'.
Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0.
BUILD FAILED in 3s
3 actionable tasks: 2 executed, 1 up-to-date
…

The wrapper

$ gradle wrapper && ls
build
build.gradle
gradle
gradlew
gradlew.bat
settings.gradle
src

gradle wrapper creates gradlew (Linux/macOS), gradlew.bat (Windows) and gradle/wrapper/ naming the exact Gradle version. Commit them; everyone runs ./gradlew build and gets that version. Maven's equivalent is the Maven Wrapper (mvnw).

Maven vs Gradle

Maven Gradle
Build file pom.xml (XML, describes the project) build.gradle / .kts (a script)
Steps fixed lifecycle phases flexible tasks
Commands mvn clean package, mvn test gradle build, gradle test, gradle run
Speed good incremental builds and a build cache
Common in many companies, Spring Boot projects Android, large projects
Same folders, Maven Central, coordinates

Common mistakes (and what you see)

A version that doesn't exist (<version>9.9</version> for Gson):

$ mvn -B compile
[INFO] Building chai-bill 1.0.0
[INFO] BUILD FAILURE
[ERROR] Failed to execute goal on project chai-bill: Could not resolve dependencies for project in.syntaxpilot:chai-bill:jar:1.0.0
[ERROR]     Could not find artifact com.google.code.gson:gson:jar:9.9 in central-mirror (file:///usr/share/maven-repo)
…

A test file in src/main/java:

$ mvn -B compile
[INFO] Building chai-bill 1.0.0
[INFO] --- resources:3.3.0:resources (default-resources) @ chai-bill ---
[INFO] --- compiler:3.10.1:compile (default-compile) @ chai-bill ---
[ERROR] COMPILATION ERROR : 
[ERROR] src/main/java/in/syntaxpilot/chai/BillTest.java:[3,29] package org.junit.jupiter.api does not exist
[ERROR] src/main/java/in/syntaxpilot/chai/BillTest.java:[4,36] package org.junit.jupiter.api does not exist
[INFO] BUILD FAILURE
…

Running Maven outside the project:

$ cd ~ && mvn -B package
[INFO] BUILD FAILURE
[ERROR] The goal you specified requires a project to execute but there is no POM in this directory (/home/student). Please verify you invoked Maven from the correct directory. -> [Help 1]
…
Mistake What you see Fix
Library not on the compile classpath error: package com.google.gson does not exist declare it as a dependency
Compiled with a jar, run without it NoClassDefFoundError: com/google/gson/Gson let the build tool run it, or put the jar on the run classpath
A version that doesn't exist Could not find artifact com.google.code.gson:gson:jar:9.9 check the version on the library's page
Test in src/main/java package org.junit.jupiter.api does not exist move it to src/test/java
mvn in the wrong folder there is no POM in this directory cd into the project
A failing test BUILD FAILURE, no jar fix the code or the test

Mini project: use your own library from another project

mvn install copies chai-bill-1.0.0.jar into your local repository. A second project, stall-screen, can then depend on it like any library:

<dependency>
  <groupId>in.syntaxpilot</groupId>
  <artifactId>chai-bill</artifactId>
  <version>1.0.0</version>
</dependency>
package in.syntaxpilot.screen;

import in.syntaxpilot.chai.Bill;

public class Screen {
    public static void main(String[] args) {
        for (int cups : new int[]{1, 10, 20})
            System.out.println(cups + " cups: Rs " + Bill.total(cups, 15));
    }
}

After mvn package in stall-screen, running it (with its dependencies on the classpath) prints:

1 cups: Rs 15
10 cups: Rs 135
20 cups: Rs 270

Practice

1. Where do these files go in a Maven project: Bill.java, BillTest.java, prices.properties?

Answer

src/main/java/<package folders>/Bill.java, src/test/java/<package folders>/BillTest.java, src/main/resources/prices.properties.

2. You use Mockito only in tests. Which scope (Maven) and configuration (Gradle)?

Answer

Maven <scope>test</scope>; Gradle testImplementation.

3. Which phases run with mvn install?

Answer

validate, compile, test, package, verify, install (every phase up to install).

4. Build the chai-bill project with Maven, break a test, and run mvn package. Is a jar made?

Answer

No. The test phase fails (Tests run: 2, Failures: 1), Maven prints BUILD FAILURE, and package never runs.

5. Arjun gets NoClassDefFoundError after compiling by hand. What happened?

Answer

The library was on the compile classpath but not on the run classpath. Use gradle run (or the jar on -cp when running), or let the build tool package the app.

Quick quiz

A test expects 150 but Bill.total(10, 15) returns 135. You run mvn package. Is the jar built? A) Yes B) No: the test phase fails first C) Yes, with a warning D) Only after mvn test

Answer

B. package runs every phase before it, including test; a failing test means BUILD FAILURE and no jar.

Interview questions

  1. What does a build tool do? Manages dependencies (downloads them with their transitive dependencies), compiles, runs tests, packages, and gives every developer the same commands.
  2. What are Maven coordinates? groupId:artifactId:version, which uniquely name a library.
  3. What is a transitive dependency? A dependency of one of your dependencies, added automatically.
  4. Explain the Maven lifecycle. validate, compile, test, package, verify, install, deploy; running a phase runs all phases before it.
  5. mvn install vs mvn deploy? install copies the artifact into the local ~/.m2; deploy uploads it to a remote repository.
  6. Difference between implementation and testImplementation? The first is for the app's code; the second only for tests.
  7. Why commit the Gradle wrapper? So everyone (and CI) builds with exactly the same Gradle version.
  8. Maven vs Gradle? Maven: XML, fixed lifecycle, simple and strict. Gradle: a build script, flexible tasks, incremental builds; standard for Android.

Glossary

Term Meaning
Library ready-made code shipped as a .jar
Dependency a library your project needs
Transitive dependency a dependency of a dependency
Classpath where Java looks for classes (compile classpath and run classpath are separate)
NoClassDefFoundError a class that was there at compile time is missing at run time
Build tool a program that downloads dependencies, compiles, tests and packages with standard commands
Maven a build tool configured with pom.xml
Gradle a build tool configured with a build.gradle script
POM Project Object Model, Maven's pom.xml
Coordinates groupId:artifactId:version
Scope where a Maven dependency is available (compile, test, provided, runtime)
Maven Central the main public repository of Java libraries
Local repository ~/.m2/repository, the downloaded jars on your machine
Lifecycle / phase Maven's ordered build steps (compile, test, package, ...)
Plugin does the work of a phase or task (compiler, surefire, jar)
Surefire Maven's plugin that runs unit tests
Task a step in a Gradle build (compileJava, test, build)
Incremental build only redo what changed (UP-TO-DATE)
Wrapper gradlew / mvnw: a script that uses a fixed tool version
Convention over configuration follow standard layouts and configure only what differs

Summary

  • Jars by hand mean two classpaths to get right and different setups on every laptop.
  • A build tool: one build file, a central repository, standard folders and one command.
  • Maven: src/main/java, src/test/java, pom.xml with coordinates, dependencies and scopes; mvn package runs compile, test and package in order; jars live in ~/.m2.
  • Gradle: the same folders, build.gradle with implementation / testImplementation, tasks, incremental builds, and the wrapper.
  • A failing test fails the build: no jar.
  • Next episode: design patterns: Singleton, Factory, Builder, Observer and Strategy.