Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 41 ยท Practice and Review

Maven Cheat Sheet

One-page Maven cheat sheet: everyday commands, lifecycle phases, dependency scopes, a POM skeleton, command-line flags and a troubleshooting table for common build errors.

This page is a quick reference for the things you look up most often while working with Maven: commands, lifecycle phases, dependency scopes, a minimal POM, command-line flags and fixes for common errors. It assumes you know the ideas already; each section links to the lesson that explains them.

Maven cannot run on this site, so every command and XML snippet is read-only. Two runnable Java stand-ins model the scope matrix and the flag meanings so you can query them. They are models of Maven's rules, not Maven.

Four commands for 90 percent of days

mvn clean verify Full build with tests.
mvn install Put the jar in ~/.m2.
dependency:tree See what you really got.
help:effective-pom See the merged POM.

Add -pl and -am when only part of a big build matters.

1 / 2

Everyday commands

Terminal
mvn -v                         # Maven, Java and OS versions
mvn clean                      # delete target/
mvn compile                    # compile main sources
mvn test                       # compile and run unit tests
mvn package                    # build the jar/war in target/
mvn verify                     # package plus integration tests and checks
mvn install                    # copy the artifact to ~/.m2/repository
mvn deploy                     # upload to a remote repository
mvn clean install              # clean first, then install
mvn archetype:generate         # create a project from a template
./mvnw verify                  # same, through the wrapper (mvnw.cmd on Windows)

See Your First Maven Project and Installing Maven and the Wrapper.

Inspection goals

Terminal
mvn help:effective-pom                     # POM after inheritance and profiles
mvn help:effective-settings                # settings.xml after merging
mvn help:active-profiles                   # which profiles are on
mvn dependency:tree                        # resolved dependency tree
mvn dependency:tree -Dverbose              # include omitted duplicates and why
mvn dependency:analyze                     # unused declared / used undeclared
mvn dependency:resolve-plugins             # download plugins ahead of time
mvn versions:display-dependency-updates    # newer versions available
mvn versions:set -DnewVersion=1.2.0        # change version across modules

Lifecycle phases

The default lifecycle runs top to bottom, and a phase runs every earlier phase first. See Lifecycles and Phases.

Phase What happens (jar packaging)
validate Check the project is correct and complete
process-resources Copy src/main/resources to target/classes (with filtering)
compile Compile src/main/java
process-test-resources Copy test resources
test-compile Compile src/test/java
test Run unit tests (Surefire)
package Build the jar
pre-integration-test, integration-test, post-integration-test Run integration tests (Failsafe)
verify Check results of integration tests and quality gates
install Copy the artifact to the local repository
deploy Upload to a remote repository

Other lifecycles: clean (pre-clean, clean, post-clean) and site (site, site-deploy). Run a single goal with mvn plugin:goal, for example mvn compiler:compile.

Dependency scopes

Scope Compile classpath Test classpath Runtime classpath Passed to consumers
compile (default) yes yes yes yes
provided yes yes no no
runtime no yes yes yes (as runtime)
test no yes no no
system yes yes no no
import only in dependencyManagement, type pom, to import a BOM

optional is a flag, not a scope: an optional dependency is used by your project but not passed on. system is deprecated. See Dependency Scopes.

Java Which classpath sees it?

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.

The table in the lesson and the map in the code carry the same information. A servlet API shows up for compiling and testing but is not on the runtime classpath, because the server supplies it.

POM skeleton

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
                             https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>demo</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>jar</packaging>

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

  <dependencyManagement>
    <dependencies>
      <!-- versions only; nothing is added to the classpath here -->
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.11.4</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <!-- default plugin versions and configuration -->
    </pluginManagement>
    <plugins>
      <!-- plugins that must run in this project -->
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>ci</id>
      <!-- settings applied with -Pci -->
    </profile>
  </profiles>
</project>

Related lessons: The POM File, Properties and Build Settings, Parent POMs and the Effective POM.

Multi-module parent

XML
<packaging>pom</packaging>
<modules>
  <module>core</module>
  <module>service</module>
  <module>app</module>
</modules>

Child POMs declare <parent> with the parent's groupId, artifactId and version. See Multi-Module Builds and the Reactor.

Command-line flags

Flag Meaning
-D<name>=<value> Set a system property (-DskipTests, -Dtest=MyTest)
-P<id>[,<id>] Activate profiles; -P!id deactivates one
-pl a,b Build only these modules
-am Also make: the modules the selected ones depend on
-amd Also make dependents
-rf :module Resume the reactor from a module
-T 1C Parallel build, one thread per CPU core
-o Offline mode, use only the local repository
-U Force-update SNAPSHOTs and missing releases
-q Quiet, errors only
-X Debug output
-e Show full stack traces for errors
-ntp No transfer progress (cleaner CI logs)
-B Batch mode, no prompts or colors
-f path/pom.xml Use another POM file
-fae, -ff Fail at end, fail fast (the default)
-DskipTests Compile tests but do not run them
-Dmaven.test.skip=true Do not even compile tests

See The Command Line Toolbox.

Java Explain a command

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.

Tokens that are values of a flag (service, 1C) are skipped by the simple loop, while the last token is read as the phase. A real argument parser is more careful, but the meanings are the ones in the table.

Coordinates, versions and repositories

Item Example
Coordinates groupId:artifactId:version, optional :packaging:classifier
Repository path ~/.m2/repository/org/example/app/1.0/app-1.0.jar
Snapshot 1.0.0-SNAPSHOT, mutable, never release with one
Settings files ~/.m2/settings.xml (user), ${maven.home}/conf/settings.xml (global)
Project config .mvn/maven.config, .mvn/jvm.config, .mvn/wrapper/maven-wrapper.properties
Property reference ${project.version}, ${project.basedir}, ${env.HOME}, ${my.property}

See Coordinates, Repositories and the Local Cache and settings.xml, Mirrors and Credentials.

Dependency management at a glance

XML
<!-- import a BOM so versions are managed for you -->
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-dependencies</artifactId>
      <version>3.4.1</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<!-- exclude a transitive dependency -->
<dependency>
  <groupId>com.example</groupId>
  <artifactId>library</artifactId>
  <version>2.1.0</version>
  <exclusions>
    <exclusion>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
    </exclusion>
  </exclusions>
</dependency>

Mediation: the nearest definition in the tree wins; on a tie, the first declared wins; your own direct declaration always wins. See Transitive Dependencies and Mediation and Managing Versions.

Common plugins

Plugin Purpose Typical command
maven-compiler-plugin Compile sources mvn compile
maven-surefire-plugin Unit tests mvn test
maven-failsafe-plugin Integration tests mvn verify
maven-jar-plugin Build the jar mvn package
maven-shade-plugin Build an uber jar mvn package
maven-enforcer-plugin Enforce rules (Java version, no duplicates) mvn validate
maven-dependency-plugin Inspect dependencies mvn dependency:tree
versions-maven-plugin Update versions mvn versions:set
jacoco-maven-plugin Code coverage mvn verify
maven-source-plugin, maven-javadoc-plugin Sources and docs jars mvn package

Troubleshooting table

Symptom Likely cause Try
invalid target release: 25 Build runs on an older JDK Check mvn -v and JAVA_HOME; use maven.compiler.release
Could not resolve dependencies Typo, missing repository, offline, or a bad cache Check coordinates; run mvn -U; delete the artifact's folder in ~/.m2
Plugin ... not found Wrong plugin coordinates or no network Add a version; check mirrors
NoSuchMethodError at run time Two versions of a library, the older one won mvn dependency:tree -Dverbose; pin in dependencyManagement
ClassNotFoundException for a transitive class Over-broad exclusion or a missing runtime dependency Remove the exclusion or add a runtime dependency
Tests not running Name does not match *Test, Test*, *Tests Rename or set includes; check for -DskipTests
Resources show ${...} Filtering is off Enable <filtering>true</filtering> on the resource folder
PKIX or certificate error A proxy re-signs HTTPS traffic Import the company certificate into the JDK trust store
OutOfMemoryError Large build or too small heap Set -Xmx in .mvn/jvm.config
Snapshot is stale Daily update check not reached Run mvn -U
Wrong profile active Property, JDK or OS activation matched mvn help:active-profiles
Different result in CI Different Java, Maven or cache Use the wrapper; compare mvn -v

See Troubleshooting Common Maven Errors and Diagnosing Dependency Conflicts.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You want to build only the service module and the modules it depends on. Which flags do you use?

    -pl selects the module and -am (also make) adds the modules it depends on. -amd would add modules that depend on it.
  2. 2. Which option skips running tests but still compiles them?

    -DskipTests compiles test classes and skips running them. maven.test.skip also skips test compilation.
  3. 3. A dependency has scope provided. On which classpath is it NOT present?

    provided is for compiling and testing; the runtime (such as a server) is expected to supply the library.
  4. 4. Which command shows why Maven omitted a duplicate library version?

    The verbose dependency tree lists omitted duplicates and the reason for each.

Summary

  • mvn clean verify is the everyday build; install shares the jar locally; deploy publishes it.
  • A phase runs all earlier phases; goals are run with plugin:goal.
  • Scopes decide which classpaths see a dependency, and mediation chooses nearest-first.
  • -pl, -am, -T, -o, -U, -q and -X cover most command-line needs.
  • When something breaks, check mvn -v, the effective POM and the verbose dependency tree first.

Looking for practice? Revisit the Maven interview questions or the practice exercises.