Learn Java · 13/15

Build Tools and Dependency Management

8 min read

Build Tools and Dependency Management 🧰

Welcome to the world of Java build tools and dependency management! Don't worry, it's not as scary as it sounds. Think of these tools as your personal assistants for your Java projects. They handle the tedious, repetitive tasks, so you can focus on the fun part: writing code!

The Problem Before Build Tools 🤔

Imagine you're building a complex Lego castle. You need specific Lego pieces (libraries or dependencies) from different sets. Without a plan, you'd have to:

  • Manually find and download each Lego set.
  • Figure out which pieces you need from each set.
  • If one set gets an update with cooler pieces, you have to manually replace the old ones.
  • When you want to share your amazing castle design with a friend, you have to give them a huge box of all the pieces and a long, complicated instruction manual you wrote yourself.

This is what Java development was like before build tools. Developers had to manually manage libraries (dependencies), compile their code, run tests, and package their applications. It was a recipe for chaos and a lot of "it works on my machine" moments.


1. Introduction to Maven: The Project Object Model (POM) 📄

What is Maven?

Maven is a powerful build automation tool that simplifies the process of building, reporting, and documenting Java projects. At its core, it's a project management tool that provides a uniform build system.

The Problem Maven Solves

Remember our Lego castle chaos? Maven is like having a master blueprint and an automated Lego-sorting robot. It solves the problem of inconsistent project structures and manual dependency management. It enforces a standard way to build projects, making it easier for anyone to understand and work on them.

The Heart of Maven: pom.xml

Every Maven project has a pom.xml file at its root. This file is the Project Object Model. Think of it as the brain of your project. It's an XML file that contains information about the project and configuration details used by Maven to build the project.

Here's a minimalistic pom.xml file:

xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.freecodecamp</groupId>
    <artifactId>my-awesome-app</artifactId>
    <version>1.0-SNAPSHOT</version>

</project>

Let's break down these core elements (The GAV Coordinates):

  • <modelVersion>: This is the version of the POM model itself. You'll almost always see it as 4.0.0. It's like knowing which version of the blueprint instructions you are using.
  • <groupId>: This is a unique identifier for your organization or group that created the project. It usually follows the reverse domain name convention (e.g., org.apache.maven).
  • <artifactId>: This is the name of your project. Think of it as the name of your Lego castle, like "The Epic Dragon Fortress".
  • <version>: This specifies the version of your project. SNAPSHOT indicates that the project is currently in development.

These three elements (groupId, artifactId, and version) are often called the GAV coordinates. They uniquely identify a project in the vast universe of Java projects.


2. Managing External Dependencies and Plugins 🧩

The Dependency Dilemma

Modern applications are rarely built from scratch. We stand on the shoulders of giants by using external libraries and frameworks. For example, you might need a library for logging (like Log4j) or for making HTTP requests (like Apache HttpClient).

The problem is managing these "external pieces." You need to find the correct versions, download the JAR files, and add them to your project's classpath. What if your library needs another library to work? This is called a "transitive dependency," and it can become a real headache to manage manually.

Maven to the Rescue: The <dependencies> Block

Maven automates this entire process. You simply declare the dependencies you need in your pom.xml inside a <dependencies> section.

Let's say we want to use the popular JUnit 5 library for testing. We would add this to our pom.xml:

xml
<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.8.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

What just happened?

  • We added a <dependency> block for JUnit.
  • We provided its groupId, artifactId, and version.
  • The magic: When you build your project, Maven will automatically download the junit-jupiter-api-5.8.2.jar file (and any libraries it depends on!) from a central repository and make it available to your project.
  • <scope>test</scope>: This is important. It tells Maven that this dependency is only needed for running tests and should not be included in the final packaged application.

What are Plugins? 🛠️

Plugins are the real workhorses of Maven. They are responsible for doing the actual work, like compiling code, running tests, and packaging your application. Most of the core functionality of Maven is implemented as plugins.

For example, to compile your Java code, Maven uses the maven-compiler-plugin. You can configure plugins in the <build> section of your pom.xml.

Here’s how you might configure the compiler plugin to use Java 11:

xml
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>11</source>
                <target>11</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Interesting Fact: The central place where Maven downloads all these dependencies from is called the Maven Central Repository. It's a massive, free library of almost every open-source Java library you can imagine!


3. Understanding the Maven Build Lifecycle 🔄

What is a Build Lifecycle?

A build lifecycle is a well-defined sequence of phases. When you run a Maven command, you are actually running a phase in a lifecycle. Each phase represents a stage in the build process.

The Problem it Solves

Imagine giving instructions to build our Lego castle. You wouldn't just say "build it!" You'd have steps: "gather the pieces," "build the foundation," "build the walls," "build the towers," etc. The Maven build lifecycle provides this standardized sequence of steps for building your software.

The Default Lifecycle

The main and most important lifecycle in Maven is the default lifecycle. Here are some of its most frequently used phases, in order:

  1. validate: Validates that the project is correct and all necessary information is available.
  2. compile: Compiles the source code of the project.
  3. test: Runs the tests using a suitable unit testing framework.
  4. package: Takes the compiled code and packages it in its distributable format, such as a JAR or WAR file.
  5. verify: Runs any checks to verify the package is valid and meets quality criteria.
  6. install: Installs the package into the local repository, for use as a dependency in other projects locally.
  7. deploy: Copies the final package to a remote repository for sharing with other developers and projects.

How it Works in Practice

When you execute a Maven command, you specify a phase. Maven will then execute all the phases up to and including the one you specified.

  • mvn compile: This will run validate and then compile.
  • mvn test: This will run validate, compile, and then test.
  • mvn package: This will run all phases up to package. This is one of the most common commands you'll use.

Under the Hood: Plugins are what actually execute during these phases. For example, during the compile phase, the maven-compiler-plugin's compile goal is executed.


4. Gradle Basics: An Alternative to Maven 🐘

Why Another Build Tool?

While Maven is fantastic and widely used, some developers felt its XML-based configuration was a bit verbose and rigid. This led to the creation of Gradle.

What is Gradle?

Gradle is another powerful build automation tool that builds upon the concepts of Maven but offers more flexibility and a more concise way to define your builds.

The Problem Gradle Solves

Gradle addresses the verbosity of Maven's XML. Instead of XML, Gradle build scripts are written in Groovy or Kotlin DSL (Domain Specific Language). This often results in shorter, more readable build files. Gradle also tends to be faster than Maven due to its advanced caching mechanisms.

Gradle's Build File: build.gradle

The equivalent of Maven's pom.xml in Gradle is the build.gradle (for Groovy) or build.gradle.kts (for Kotlin) file.

Here's how you might define dependencies and specify the Java version in a build.gradle file (Groovy DSL):

groovy
plugins {
    id 'java'
}

group 'com.freecodecamp'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2'
}

java {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

Key Differences from Maven:

  • Configuration: Groovy/Kotlin code vs. XML. This allows for more programmatic and flexible build logic.
  • Performance: Gradle often has better performance due to features like incremental builds and a build cache.
  • Flexibility: Gradle is generally considered more flexible and customizable than Maven.

Which one should I use?

Both Maven and Gradle are excellent choices and are widely used in the industry.

  • Choose Maven if: You prefer a more rigid and conventional project structure. It has been around longer and has a vast amount of documentation and community support. Many enterprise environments have standardized on Maven.
  • Choose Gradle if: You prefer more concise build scripts and need more flexibility. It's very popular in the Android development world and is gaining a lot of traction in other areas of Java development.

Funny Exaggeration: Choosing between Maven and Gradle is like choosing between a classic, reliable car that everyone knows how to drive (Maven) and a sleek, modern electric car with all the new gadgets (Gradle). Both will get you to your destination, but the driving experience is different.


Additional Resources 📚

Challenge

You are tasked with creating a complete Maven pom.xml file for a new Java project. Your pom.xml must be well-formed and meet all the requirements below.

Project Requirements:

  1. Project Root: The root element must be <project> and should include the standard XML namespace and schema location attributes for Maven POM 4.0.0.
  2. Model Version: The <modelVersion> must be set to 4.0.0.
  3. Project Coordinates (GAV):
    • groupId: com.example.webtier
    • artifactId: string-utils
    • version: 1.2.0-SNAPSHOT
  4. Dependencies: You need to declare two dependencies inside a <dependencies> block:
    • JUnit Jupiter:
      • groupId: org.junit.jupiter
      • artifactId: junit-jupiter-api
      • version: 5.9.1
      • scope: test
    • Apache Commons Lang:
      • groupId: org.apache.commons
      • artifactId: commons-lang3
      • version: 3.12.0
      • This dependency should use the default compile scope.
  5. Build Configuration:
    • Add a <build> section containing a <plugins> block.
    • Configure the maven-compiler-plugin to enforce Java 11.
      • Plugin groupId: org.apache.maven.plugins
      • Plugin artifactId: maven-compiler-plugin
      • Plugin version: 3.8.1
    • Inside the plugin's <configuration>, set both <source> and <target> to 11.

Expected result

Your pom.xml file should look like the following. The order of elements like groupId, artifactId, and version within a block does not matter, but the overall structure must be correct.

xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example.webtier</groupId>
    <artifactId>string-utils</artifactId>
    <version>1.2.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.9.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
xml

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.