Maven Build Tool

Maven cheatsheet — build, test, package, install Java projects. mvn clean install, mvn test, mvn -DskipTests package, mvn dependency:tree. Full Maven lifecycle reference.

6 min read

What it is

Maven is a build automation and project management tool used primarily for Java projects, simplifying dependency management, compilation, testing, and packaging.

Installation

Linux

# Using package manager (Debian/Ubuntu)
sudo apt update
sudo apt install maven

# Using package manager (Fedora/CentOS/RHEL)
sudo yum install maven
# or
sudo dnf install maven

# Downloading from Apache Maven website
# Check https://maven.apache.org/download.cgi for latest version
wget https://dlcdn.apache.org/maven/maven-3/3.9.6/binar
y/apache-maven-3.9.6-bin.tar.gz
tar xzvf apache-maven-3.9.6-bin.tar.gz
export M2_HOME=/path/to/apache-maven-3.9.6
export PATH=$M2_HOME/bin:$PATH
# Add these exports to your shell profile (~/.bashrc, ~/.zshrc) for persistence

macOS

# Using Homebrew
brew install maven

Windows

# Downloading from Apache Maven website
# Check https://maven.apache.org/download.cgi for latest version
# Download the .zip file, extract it to a directory (e.g., C:\Program Files\Maven)
# Set M2_HOME environment variable to the extracted directory (e.g., C:\Program Files\Maven\apache-maven-3.9.6)
# Add %M2_HOME%\bin to your system's PATH environment variable

Core Concepts

  • Project Object Model (POM): The pom.xml file is the central configuration file for a Maven project. It describes the project’s structure, dependencies, build process, plugins, and more.
  • Dependencies: Maven manages external libraries (JARs) your project needs. You declare them in the pom.xml, and Maven downloads them from repositories (like Maven Central).
  • Build Lifecycle: Maven has predefined lifecycles (e.g., default, clean, site) that consist of phases (e.g., validate, compile, test, package, install, deploy). Executing a phase triggers all preceding phases in that lifecycle.
  • Goals: Each plugin provides goals, which are specific tasks that can be executed. Goals are bound to lifecycle phases.
  • Repositories: Locations where Maven artifacts (JARs, POMs) are stored. The default is Maven Central. You can configure local and remote repositories.
  • Plugins: Extend Maven’s functionality. Common plugins include maven-compiler-plugin, maven-surefire-plugin (for tests), maven-jar-plugin, maven-war-plugin.

Commands / Usage

Basic Build Execution

  • Clean and Build:

    mvn clean install
    

    Cleans the project (removes previous build artifacts) and then runs all phases up to install (compiles, tests, packages, and installs the artifact in the local repository).

  • Compile:

    mvn compile
    

    Compiles the source code of the project.

  • Test:

    mvn test
    

    Runs the unit tests.

  • Package:

    mvn package
    

    Compiles, tests, and packages the code into its distributable format (e.g., JAR, WAR).

  • Install:

    mvn install
    

    Installs the package into the local Maven repository, for use as a dependency in other local projects.

  • Deploy:

    mvn deploy
    

    Deploys the package to a remote repository, making it available for other developers and projects.

  • Clean:

    mvn clean
    

    Deletes the project’s build output directory (usually target/).

Project Information and Generation

  • Generate Project Structure:

    mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
    

    Creates a new Maven project with a basic directory structure using a specified archetype.

  • Display Project Information:

    mvn help:effective-pom
    

    Displays the fully resolved POM, including parent POMs and plugin configurations.

  • List Available Goals:

    mvn help:describe -Dplugin=org.apache.maven.plugins:maven-compiler-plugin
    

    Describes a specific plugin and its goals.

Dependency Management

  • Dependency Tree:

    mvn dependency:tree
    

    Displays the project’s dependency tree, showing direct and transitive dependencies. Useful for diagnosing conflicts.

  • Resolve Dependencies:

    mvn dependency:resolve
    

    Resolves project dependencies and lists them.

  • Analyze Dependencies:

    mvn dependency:analyze
    

    Analyzes the project’s dependencies to identify unused declared dependencies and used but undeclared dependencies.

Running Applications

  • Run Main Class (if packaged as executable JAR):

    mvn exec:java -Dexec.mainClass="com.mycompany.app.App"
    

    Executes the main method of a specified class.

  • Run Application with Specific JAR:

    mvn exec:java -Dexec.jar="/path/to/my-app.jar" -Dexec.mainClass="com.mycompany.app.App"
    

    Executes the main method of a specified class within a given JAR.

Plugin Execution

  • Run a Specific Plugin Goal:

    mvn compiler:compile
    

    Executes the compile goal of the maven-compiler-plugin.

  • Run a Specific Plugin Goal with Parameters:

    mvn surefire-report:report-only -Dsurefire.reportsdir=target/surefire-reports
    

    Executes the report-only goal of the maven-surefire-report-plugin, specifying a directory for reports.

Profiles

  • Build with a Specific Profile:

    mvn install -P production
    

    Activates the production profile during the build.

  • Build with Multiple Profiles:

    mvn install -P dev,testing
    

    Activates both dev and testing profiles.

Other Useful Flags

  • Skip Tests:

    mvn install -DskipTests
    

    Skips running tests during the build.

  • Offline Mode:

    mvn install -o
    

    Runs Maven in offline mode. It will not attempt to connect to any network resources. Dependencies must be in the local repository.

  • Non-Recursive Build:

    mvn install -N
    

    Do not recurse into sub-modules.

  • Show Version:

    mvn -v
    

    Displays the Maven version and Java version.

Common Patterns

  • Build a WAR file for a web application:

    mvn clean package
    

    (Assumes maven-war-plugin is configured in pom.xml)

  • Run integration tests (requires failsafe plugin setup):

    mvn verify
    

    The verify phase is typically used for integration tests.

  • Check for code quality issues (e.g., with Checkstyle, PMD):

    mvn verify site
    

    (Requires relevant plugins configured in pom.xml to run during the verify or site phases)

  • Update dependencies in a project (forces re-download):

    mvn clean install -U
    

    The -U flag forces an update of the metadata and checksums for remote snapshots and releases.

  • Build a specific module in a multi-module project:

    cd my-module
    mvn install
    

    Navigate to the module’s directory and run the desired command. Maven will build only that module and its dependencies.

  • Executing a specific test class:

    mvn test -Dtest=com.mycompany.app.MyTestClass
    

    Runs only the tests within MyTestClass.

  • Executing tests matching a pattern:

    mvn test -Dtest=**/My*Test
    

    Runs all test classes whose names start with "My" and end with "Test".

Gotchas

  • Transitive Dependency Conflicts: When multiple dependencies rely on different versions of the same transitive dependency, Maven might pick one, potentially leading to runtime errors. Use mvn dependency:tree to identify conflicts and explicitly declare the desired version in your pom.xml using the <dependencyManagement> section.
  • Snapshot Versions: Snapshot versions (-SNAPSHOT) are dynamic and can change. Using -U forces Maven to check for updated snapshots. Be cautious when deploying snapshot versions to remote repositories.
  • Plugin Prefix Resolution: Maven uses a prefix to map plugins (e.g., compiler maps to org.apache.maven.plugins:maven-compiler-plugin). If a plugin isn’t found, ensure it’s correctly configured in the pom.xml or that you’re using the full artifact ID.
  • Local Repository Location: Maven stores downloaded artifacts in a local repository, typically ~/.m2/repository. If this directory becomes corrupted or you need to clear it, manually deleting contents can resolve issues, but be aware it will force re-downloading everything.
  • Build Failure on First Run: Sometimes, especially with complex projects or network issues, the first build might fail. Running mvn clean install again often resolves transient problems.
  • Profile Activation: Profiles can be activated in several ways (<activeByDefault>, -P flag, OS settings, JDK version). Understanding how profiles are activated is crucial for consistent builds.
  • mvn install vs. mvn deploy: install puts artifacts into your local repository, useful for local development. deploy pushes artifacts to a remote repository, making them available to others. Don’t confuse their purposes.