Maven Cheat Sheet
Maven Cheat Sheet Overview
This cheat sheet provides a quick reference for essential Maven commands, configurations, lifecycle phases, profile management, and plugin executions. It's designed to help developers efficiently manage their Java projects.
Generate Project from Archetype
Use the archetype:generate
goal to create new Maven projects based on predefined templates (archetypes).
mvn archetype:generate
Example: Generating a Dropwizard project.
mvn archetype:generate \
-DarchetypeGroupId=io.dropwizard.archetypes \
-DarchetypeArtifactId=java-simple \
-DarchetypeVersion=4.0.8
Example: Using the JDK8 QuickStart archetype.
mvn org.apache.maven.plugins:maven-archetype-plugin:3.1.2:generate \
-DarchetypeArtifactId="archetype-quickstart-jdk8" \
-DarchetypeGroupId="com.github.ngeor" \
-DarchetypeVersion="2.8.1" \
-DgroupId="com.example" \
-DartifactId="demo"
Example Output
[INFO] --- archetype:3.1.2:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Interactive mode
[INFO] Archetype repository not defined. Using the one from [com.github.ngeor:archetype-quickstart-jdk8:3.0.0] found in catalog remote
[INFO] Using property: groupId = com.example
[INFO] Using property: artifactId = demo
Define value for property 'version' 1.0-SNAPSHOT: :
[INFO] Using property: package = com.example
Confirm properties configuration:
groupId: com.example
artifactId: demo
version: 1.0-SNAPSHOT
package: com.example
Y: :
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Archetype: archetype-quickstart-jdk8:2.8.1
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.example
[INFO] Parameter: artifactId, Value: demo
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: package, Value: com.example
[INFO] Parameter: packageInPathFormat, Value: com/example
[INFO] Parameter: package, Value: com.example
[INFO] Parameter: groupId, Value: com.example
[INFO] Parameter: artifactId, Value: demo
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Project created from Archetype in dir: D:\Users\ghays\poc\demo
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:18 min
[INFO] Finished at: 2024-09-19T16:37:28-05:00
[INFO] ------------------------------------------------------------------------
Maven Configuration Files
The .mvn
directory at the project's root contains configuration files:
maven.config
jvm.config
extensions.xml
The .mvn/maven.config
file allows specifying arguments per line, starting from Maven 3.9.0.
-T3
-U
--fail-at-end
Maven Configuration References
Project Information Commands
Get Project Version
Retrieve the current project version.
mvn -q -Dexec.executable="echo" -Dexec.args='${project.version}' --non-recursive exec:exec
Output: 1.0.0-SNAPSHOT
Property References
Accessing built-in project properties:
project.build.sourceDirectory
project.build.scriptSourceDirectory
project.build.testSourceDirectory
project.build.outputDirectory
project.build.testOutputDirectory
project.build.directory
Reference: Maven project.build.directory
Testing Commands
Run a Single Test Case
mvn -Dtest=<file> test
Run a Single Test Method
mvn -Dtest=TestClass#testMethod test
Debug Tests
Tests will pause and await a remote debugger on port 5005.
mvn -Dtest=<file> -Dmaven.surefire.debug test
Further details: Maven - Debugging Tests
Related: How to run unit test with Maven
Dependency Management
Get a Dependency Tree
Visualize the project's dependency structure.
mvn dependency:tree
Filter the tree for a specific group ID.
mvn dependency:tree | grep -n -A 5 -B 20 "io.github"
Analyze Dependencies
Identify unused and declared dependencies.
mvn dependency:analyze
Purge Local Maven Repository
Remove artifacts from the local repository.
mvn dependency:purge-local-repository
Add Local JAR Files
Include local JARs as dependencies.
<dependency>
<groupId>com.sample</groupId>
<artifactId>sample</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/yourJar.jar</systemPath>
</dependency>
Reference: How to add local jar files to a Maven project?
Alternatively, use install-file
:
mvn install:install-file \
-Dfile=<path-to-file> \
-DgroupId=<group-id> \
-DartifactId=<artifact-id> \
-Dversion=<version> \
-Dpackaging=<packaging> \
-DgeneratePom=true
Repository and Settings Management
Override Local Repository
Specify an alternative location for the local Maven repository.
mvn -Dmaven.repo.local=/build/.m2/repository
Custom User Settings File
Use a specific settings.xml
file.
-s,--settings <arg> e.g.
mvn -s ~/custom/settings.xml
Use Global Settings File
Specify a global settings file.
-gs,--global-settings <arg> e.g.
mvn -gs /build/settings.xml
Build and Output Control
Remove Platform Encoding Warning
Ensure consistent encoding by setting project.build.sourceEncoding
.
<project ...>
...
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
...
</properties>
..
</project>
Effective POM
View the fully resolved POM after inheritance and interpolation.
mvn help:effective-pom
Or save to a file:
mvn -q help:effective-pom -Deffective-pom.xml
References: What are the difference between pom.xml and effective pom in Apache Maven?, Apache Maven Help Plugin
Generate Maven Project
Create a new project using a specific archetype.
mvn -B archetype:generate \
-DarchetypeGroupId=org.apache.maven.archetypes \
-DgroupId=com.log4j.maven \
-DartifactId=dependency-example
Quick Start Example:
mvn archetype:generate \
-DarchetypeGroupId=org.apache.maven.archetypes \
-DarchetypeArtifactId=maven-archetype-quickstart
Related: Fix broken builds with this log4j Maven dependency example
Maven Lifecycle Phases
Understanding the Maven build lifecycle is crucial for executing tasks in the correct order.
Lifecycle default -> [validate, initialize, generate-sources, process-sources,
generate-resources, process-resources, compile, process-classes, generate-test-sources,
process-test-sources, generate-test-resources, process-test-resources, test-compile,
process-test-classes, test, prepare-package, package, pre-integration-test, integration-test,
post-integration-test, verify, install, deploy]
Lifecycle clean -> [pre-clean, clean, post-clean]
Lifecycle site -> [pre-site, site, post-site, site-deploy]
Profiles
Deactivate a Profile
Control profile activation from the command line.
mvn groupId:artifactId:goal -P !profile-1,!profile-2
With escaping:
mvn groupId:artifactId:goal -P \!profile-1
Alternative syntax (using `-`):
mvn groupId:artifactId:goal -P-profile-1,-profile2
Reference: De-activate a maven profile from command line
Plugins
Execute a Specific Plugin Goal by ID
Run a particular execution of a plugin.
mvn sql:execute@create-db
References: Maven plugin execution ID, Run a single Maven plugin execution?, SQL Maven Plugin#Executions
Shade or Uber JAR
Create a fat JAR, optionally minimizing its size by removing unused classes.
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<minimizeJar>true</minimizeJar>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
</project>
Reference: Selecting Contents for Uber JAR.
Release Plugin
Configure the Maven Release Plugin for preparing and performing releases.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.3</version>
<configuration>
<tagNameFormat>v@{project.version}</tagNameFormat>
</configuration>
</plugin>
Reference: Maven Release Plugin > Prepare a Release
Command Line Options
Frequently used Maven command-line options for enhanced control:
Options | Description |
---|---|
-B,--batch-mode | Run in non-interactive (batch) mode (disables output color) |
-D,--define | Define a system property |
-e,--errors | Produce execution error messages |
-f,--file | Force the use of an alternate POM file (or directory with pom.xml) |
-N,--non-recursive | Do not recurse into sub-projects |
-o,--offline | Work offline |
-P,--activate-profiles | Comma-delimited list of profiles to activate |
-pl,--projects | Comma-delimited list of specified reactor projects to build instead of all projects. A project can be specified by [groupId]:artifactId or by its relative path |
-rf,--resume-from | Resume reactor from specified project |
-s,--settings | Alternate path for the user settings file |
-U,--update-snapshots | Forces a check for missing releases and updated snapshots on remote repositories |
-v,--version | Display version information |
-X,--debug | Produce execution debug output |
See all options: Maven Command Line Options
Advanced Commands
Logging Level
Control the verbosity of Maven's output.
mvn clean package -Dorg.slf4j.simpleLogger.defaultLogLevel=DEBUG
Alternatively, configure in ${MAVEN_HOME}/conf/logging/simplelogger.properties
or via .mvn/jvm.config
.
Force Update from Remote Repository
Ensure the latest snapshots and releases are fetched.
-U,--update-snapshots e.g.
mvn -U
Log File
Redirect Maven output to a file, suppressing console output.
-l,--log-file <arg> e.g.
mvn -l maven.log
Batch Mode
Run Maven in non-interactive mode.
mvn -B
Parallel Builds
Speed up builds by utilizing multiple threads.
1 thread per available CPU core:
mvn -T 1C
Alternatively, specify a fixed number of threads:
mvn -T 4 install -- will use 4 threads
mvn -T 2C install -- will use 2 threads per available CPU core
Performance tips: Your Maven build is slow. Speed it up!, How to Speed up Your Maven Build
List Modules and Directories
Determine the build order and identify modules.
Reactor Build Order:
mvn validate
List modules by Artifact ID:
Note: On Windows, use double quotes ("
) in the awk
statement.
mvn --also-make dependency:tree | grep maven-dependency-plugin | awk '{ print $(NF-1) }'
Variant without awk
(use double quotes for Windows):
mvn -Dexec.executable='echo' -Dexec.args='${project.artifactId}' exec:exec -q
List Module Directories:
mvn -q --also-make exec:exec -Dexec.executable="pwd"
References: How to list active sub-modules in a Maven project?, How to list the Maven build/compilation sequence based on dependencies?, Maven Tips and Tricks: Advanced Reactor Options
General References
- 20+ Maven Commands and Options (Cheat Sheet)
- Maven - alternative .m2 directory
- How to Override the Maven Local Repository setting
- Maven CLI Options Reference
- Purging local repository dependencies
- What are all of the Maven Command Line Options?
- Maven logging: Maven logging and the command line and How to change maven logging level...
- Maven Commands and Options
- Maven in 5 Minutes