Maven: Dependency and Build Management

Introduction

Maven automates Java builds: compile, test, package JARs, and manage dependencies (libraries like Gson, JUnit). Real teams use pom.xml to keep projects reproducible. This chapter covers a minimal Maven project aligned with JDK 21 from install chapters and Java 21 Features.

Prerequisites

  • JDK 21 installed
  • Command line basics
  • Optional: JSON Handling Gson example

Install Maven

Download from maven.apache.org or use package managers:

bash
# macOS (Homebrew)
brew install maven
 
mvn -version

Verify Maven uses Java 21 in output.

1) Standard Directory Layout

text
my-app/
  pom.xml
  src/main/java/...        # application code
  src/main/resources/      # config files
  src/test/java/...        # tests

Maven conventions let tools and CI understand projects instantly.

2) Minimal pom.xml

maven.compiler.release 21 enables Java 21 language features.

3) Common Commands

bash
mvn compile          # compile main sources
mvn test             # run tests
mvn package          # build JAR in target/
mvn clean package    # clean then package

4) JUnit Example with @Test

Annotations (Annotations) in tests:

java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
 
class CalculatorTest {
 
    @Test
    void addsNumbers() {
        assertEquals(8, 3 + 5);
    }
}

Place under src/test/java. Run with mvn test.

5) Coordinates Explained

groupId:artifactId:version identifies dependencies in Maven Central.

IntelliJ can import Maven projects directly (Open → select pom.xml).

Common Beginner Mistakes

Wrong Java Version in pom.xml

Symptoms: cannot use record or new syntax—set release to 21.

Dependencies Without Refresh

After editing pom.xml, reload Maven project in IDE.

Putting Source in Wrong Folder

src/main/java only—not project root.

What’s Next

Gradle alternative, then Books.

FAQ

Maven vs Gradle?

Maven: XML, convention-heavy. Gradle: flexible Kotlin/Groovy DSL, popular on Android. Both fine—learn one deeply first.

Where do JARs download?

Local ~/.m2/repository cache.

How to run main class?

exec-maven-plugin or package fat JAR—advanced; IntelliJ run is enough while learning.

Spring Boot?

Builds on Maven/Gradle with starters—beyond this tutorial’s scope.

Compiler release must match installed JDK major version.