DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

  1. DZone
  2. Refcards
  3. Apache Maven 2
refcard cover
Refcard #055

Apache Maven 2

Enabling You to Build Better Java Code

Gives Java developers a wide range of execution commands, tips for debugging Mavenized builds, and a clear introduction to the Maven vocabulary.

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Matthew McCullough
Managing Partner, Ambient Ideas, LLC
Table of Contents
► About Apache Maven ► The MVN Command ► Project Object Model ► Execution Groups ► Help ► Dependencies ► Plugins ► Visualize Dependencies ► Repositories ► Property Variables ► Debugging ► Source Code Management ► Profiles ► Profile Activation ► Cutting a Release ► Archetypes ► Reports
Section 1

About Apache Maven

By Matthew McCullough

Maven is a comprehensive project information tool, whose most common application is building Java code. Maven is often considered an alternative to Ant, but as you’ll see in this Refcard, it offers unparalleled software lifecycle management, providing a cohesive suite of verification, compilation, testing, packaging, reporting, and deployment plugins.

Maven is receiving renewed recognition in the emerging development space for its convention over configuration approach to builds. This Refcard aims to give JVM platform developers a range of basic to advanced execution commands, tips for debugging Mavenized builds, and a clear introduction to the “Maven vocabulary”.

Interoperability and Extensibility

New Maven users are pleasantly surprised to find that Maven offers easy-to-write custom build-supplementing plugins, reuses any desired aspect of Ant, and can compile native C, C++, and .NET code in addition to its strong support for Java and JVM languages and platforms, such as Scala, JRuby, Groovy and Grails.

Hot Tip

All things Maven can be found at http://maven.apache.org
Section 2

The MVN Command

Maven supplies a Unix shell script and MSDOS batch file named mvn and mvn.bat respectively. This command is used to start all Maven builds. Optional parameters are supplied in a space-delimited fashion. An example of cleaning and packaging a project, then running it in a Jetty servlet container, yet skipping the unit tests, reads as follows:

​x
1
​
2
mvn clean package jetty:run –Dmaven.test.skip
3
​
Section 3

Project Object Model

The world of Maven revolves around metadata files named pom.xml. A file of this name exists at the root of every Maven project and defines the plugins, paths and settings that supplement the Maven defaults for your project.

Basic pom.xml Syntax

The smallest valid pom.xml, which inherits the default artifact type of “jar”, reads as follows:

8
1
​
2
<project>
3
        <modelVersion>4.0.0</modelVersion>
4
        <groupId>com.ambientideas</groupId>
5
        <artifactId>barestbones</artifactId>
6
        <version>1.0-SNAPSHOT</version>
7
</project>
8
​

Super POM

The Super POM is a virtual pom.xml file that ships inside the core Maven JARs, and provides numerous default settings. All projects automatically inherit from the Super POM, much like the Object super class in Java. Its contents can be viewed in one of two ways:

View Super POM via SVN

Open the following SVN viewing URL in your web browser:

3
1
​
2
http://svn.apache.org/repos/asf/maven/components/branches/maven-2.1.x/pom.xml
3
​

View Super POM via Effective-Oom

Run the following command in a directory that contains the most minimal Maven project pom.xml, listed above.

3
1
​
2
mvn help:effective-pom
3
​

Multi-Module Projects

Maven showcases exceptional support for componentization via its concept of multi-module builds. Place sub-projects in sub-folders beneath your top level project and reference each with a module tag. To build all sub projects, just execute your normal mvn command and goals from a prompt in the top-most directory.

11
1
​
2
<project>
3
  <!-- ... -->
4
  <packaging>pom</packaging>
5
  <modules>
6
    <module>servlets</module>
7
    <module>ejbs</module>
8
    <module>ear</module>
9
  </modules>
10
</project>
11
​

Artifact Vector

Each Maven project produces an element, such as a JAR, WAR or EAR, uniquely identified by a composite of fields known as groupId, artifactId, packaging, version and scope. This vector of fields uniquely distinguishes a Maven artifact from all others.

Many Maven reports and plugins print the details of a specific artifact in this colon separated fashion:

3
1
​
2
groupid:artifactid:packaging:version:scope
3
​

An example of this output for the core Spring JAR would be:

3
1
​
2
org.springframework:spring:jar:2.5.6:compile
3
​
Section 4

Execution Groups

Maven divides execution into four nested hierarchies. From most-encompassing to most-specific, they are: Lifecycle, Phase, Plugin, and Goal.

Lifecycles, Phases, Plugins and Goals

Maven defines the concept of language-independent project build flows that model the steps that all software goes through during a compilation and deployment process.

Lifecycles

Lifecycles represent a well-recognized flow of steps (Phases) used in software assembly.

Each step in a lifecycle flow is called a phase. Zero or more plugin goals are bound to a phase.

A plugin is a logical grouping and distribution (often a single JAR) of related goals, such as JARing.

A goal, the most granular step in Maven, is a single executable task within a plugin. For example, discrete goals in the jar plugin include packaging the jar (jar:jar), signing the jar (jar:sign), and verifying the signature (jar:sign-verify).

Executing a Phase or Goal

At the command prompt, either a phase or a plugin goal can be requested. Multiple phases or goals can be specified and are separated by spaces.

5
1
​
2
If you ask Maven to run a specific plugin goal, then only that goal is run. This example runs two plugin goals: compilation
3
of code, then JARing the result, skipping over any intermediate steps.
4
mvn compile:compile jar:jar
5
​

Conversely, if you ask Maven to execute a phase, all phases and bound plugin goals up to that point in the lifecycle are also executed. This example requests the deploy lifecycle phase, which will also execute the verification, compilation, testing and packaging phases.

3
1
​
2
mvn deploy
3
​

Online and Offline

During a build, Maven attempts to download any uncached referenced artifacts and proceeds to cache them in the ~/.m2/repository directory on Unix, or in the %USERPROFILE%/.m2/repository directory on Windows.

To prepare for compiling offline, you can instruct Maven to download all referenced artifacts from the Internet via the command:

3
1
​
2
mvn dependency:go-offline
3
​

If all required artifacts and plugins have been cached in your local repository, you can instruct Maven to run in offline mode with a simple flag:

3
1
​
2
mvn <phase or goal> -o
3
​

Built-In Maven Lifecycles

Maven ships with three lifecycles; clean, default, and site. Many of the phases within these three lifecycles are bound to a sensible plugin goal.

Hot Tip

The official lifecycle reference, which extensively lists all the default bindings, can be found at http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

The clean lifecycle is simplistic in nature. It deletes all generated and compiled artifacts in the output directory.

Clean Lifecycle
Lifecycle Phase Purpose
pre-clean
clean Remove all generated and compiled artifacts in preperation for a fresh build.
post-clean
Default Lifecycle
Lifecycle Phase Purpose
validate Cross check that all elements necessary for the build are correct and present.
initialize Set up and bootstrap the build process.
generate-sources Generate dynamic source code
process-sources Filter, sed and copy source code
generate-resources Generate dynamic resources
process-resources Filter, sed and copy resources files.
compile Compile the primary or mixed language source files.
process-classes Augment compiled classes, such as for code-coverage instrumentation.
generate-test-sources Generate dynamic unit test source code.
process-test-sources Filter, sed and copy unit test source code.
generate-test-resources Generate dynamic unit test resources.
process-test-resources Filter, sed and copy unit test resources.
test-compile Compile unit test source files
test Execute unit tests
prepare-package Manipulate generated artifacts immediately prior to packaging. (Maven 2.1 and above)
package Bundle the module or application into a distributable package (commonly, JAR, WAR, or EAR).
pre-integration-test
integration-test Execute tests that require connectivity to external resources or other components
post-integration-test
verify Inspect and cross-check the distribution package (JAR, WAR, EAR) for correctness.
install Place the package in the user’s local Maven repository.
deploy Upload the package to a remote Maven repository

The site lifecycle generates a project information web site, and can deploy the artifacts to a specified web server or local path.

Site Lifecycle
Lifecycle Phase Purpose
pre-site Cross check that all elements necessary for the build are correct and present.
site Generate an HTML web site containing project information and reports.
post-site
site-deploy Upload the generated website to a web server

Default Goal

The default goal codifies the author’s intended usage of the build script. Only one goal or lifecycle can be set as the default. The most common default goal is install.

9
1
​
2
<project>
3
   [...]
4
   <build>
5
      lt;defaultGoal>install</defaultGoal>
6
   </build>
7
   [...]
8
</project>
9
​
Section 5

Help

Help for a Plugin

Lists all the possible goals for a given plugin and any associated documentation.

3
1
​
2
help:describe -Dplugin=<pluginname>
3
​

Help for POMs

To view the composite pom that’s a result of all inherited poms:

3
1
​
2
mvn help:effective-pom
3
​

Help for Profiles

To view all profiles that are active from either manual or automatic activation:

3
1
​
2
mvn help:active-profiles
3
​
Section 6

Dependencies

Declaring a Dependency

To express your project’s reliance on a particular artifact, you declare a dependency in the project’s pom.xml.

Hot Tip

You can use the search engine at repository.sonatype.org to find dependencies by name and get the xml necessary to paste into your pom.xml
14
1
​
2
<project>
3
  <dependencies>
4
    <dependency>
5
         <groupId>com.yourcompany</groupId>
6
         <artifactId>yourlib</artifactId>
7
         <version>1.0</version>
8
         <type>jar</type>
9
         <scope>compile</scope>
10
    </dependency>
11
   </dependencies>
12
  <!-- ... -->
13
</project>
14
​

Standard Scopes

Each dependency can specify a scope, which controls its visibility and inclusion in the final packaged artifact, such as a WAR or EAR. Scoping enables you to minimize the JARs that ship with your product.

Scope Description
compile Needed for compilation, included in packages.
test Needed for unit tests, not included in packages.
provided Needed for compilation, but provided at runtime by the runtime container.
system Needed for compilation, given as absolute path on disk, and not included in packages.
import An inline inclusion of a POM-type artifact facilitating dependency-declaring POM snippets.
Section 7

Plugins

Adding a Plugin

A plugin and its configuration are added via a small declaration, very similar to a dependency, in the <build> section of your pom.xml.

14
1
​
2
<build>
3
  <!-- ... -->
4
  <plugins>
5
    <plugin>
6
      <groupId>org.apache.maven.plugins</groupId>
7
      <artifactId>maven-compiler-plugin</artifactId>
8
      <configuration>
9
        <maxmem>512m</maxmem>
10
     </configuration>
11
    </plugin>
12
  </plugins>
13
</build>
14
​

Common Plugins

Maven created an acronym for its plugin classes that aggregates “Plain Old Java Object” and “Maven Java Object” into the resultant word, Mojo.

There are dozens of Maven plugins, but a handful constitute some of the most valuable, yet underused features:

surefire Runs unit tests.
checkstyle Checks the code’s styling
clover Code coverage evaluation.
enforcer Verify many types of environmental conditions as prerequisites.
assembly Creates ZIPs and other distribution packages of apps and their transitive dependency JARs.

Hot Tip

The full catalog of plugins can be found at: http://maven.apache.org/plugins/index.html
Section 8

Visualize Dependencies

Users often mention that the most challenging task is identifying dependencies: why they are being included, where they are coming from and if there are collisions. Maven has a suite of goals to assist with this.

List a hierarchy of dependencies.

3
1
​
2
mvn dependency:tree
3
​

List dependencies in alphabetic form.

3
1
​
2
mvn dependency:resolve
3
​

List plugin dependencies in alphabetic form.

3
1
​
2
mvn dependency:resolve-plugins
3
​

Analyze dependencies and list any that are unused, or undeclared.

3
1
​
2
mvn dependency:analyze
3
​
Section 9

Repositories

Repositories are the web sites that host collections of Maven plugins and dependencies.

Declaring a Repository

8
1
​
2
<repositories>
3
  lt;repository>
4
  <id>JavaDotNetRepo</id>
5
    <url>https://maven-repository.dev.java.net</url>
6
  </repository>
7
</repositories>
8
​

The Maven community strongly recommends using a repository manager such as Nexus to define all repositories. This results in cleaner pom.xml files and centrally cached and managed connections to external artifact sources. Nexus can be downloaded from http://nexus.sonatype.org/

Popular Repositories

Central http://repo1.maven.org/maven2/
Java.net https://maven-repository.dev.java.net/
Codehaus http://repository.codehaus.org/
JBoss http://repository.jboss.org/maven2

Hot Tip

A near complete list of repositores can be found at http://www.mvnbrowser.com/repositories.html
Section 10

Property Variables

A wide range of predefined or custom of property variables can be used anywhere in your pom.xml files to keep string and path repetition to a minimum.

All properties in Maven begin with ${ and end with }. To list all available properties, run the following command.

3
1
​
2
mvn help:expressions
3
​

Predefined Properties (Partial List)

${env.PATH} Any OS environment variable such as EDITOR, or GROOVY_HOME. Specifically, the PATH environment variable.
${project.groupId} Any project node from the aggregated Maven pom.xml. Specifically, the Group ID of the project
${project.artifactId} Name of the artifact.
${project.basedir} Path of the pom.xml.
${settings.localRepository} The path to the user’s local repository.
${java.home} Any Java System Property. Specifically, the Java System Property path to its home.
${java.vendor} The Java System Property declaring the JRE vendor’s name.
${my.somevar} A user-defined variable.

Project properties could previously be referenced with a ${pom.basedir} prefix or no prefix at all ${basedir}. Maven now requires that you prefix these variables with the word project ${project.basedir}.

Define a Property

You can define a new custom property in your pom.xml like so:

9
1
​
2
<project>
3
   [...]
4
   <properties>
5
      <my.somevar>My Value</my.somevar>
6
   </properties>
7
   [...]
8
</project>
9
​
Section 11

Debugging

Exception Full Stack Traces

If a Maven plugin is reporting an error, to see the full detail of the exception’s stack trace run Maven with the -e flag.

3
1
​
2
mvn <yourgoal> -e
3
​

Output Debugging Info

Whenever reporting a Maven bug, or troubleshooting a problem, turn on all the debugging info by running Maven like so:

3
1
​
2
mvn <yourgoal> -X
3
​

Debug Maven Core/Plugins

Core Maven operations and plugins can be stepped through with any JPDA-compatible debugger, the most common option being Eclipse. When run in debug mode, Maven will wait for you to connect your debugger to socket port 8000 before continuing with its lifecycle.

5
1
​
2
mvnDebug <yourgoal>
3
Preparing to Execute Maven in Debug Mode
4
Listening for transport dt_socket at address: 8000
5
​

Debug a Unit Test

Your suite or an individual unit test can be debugged in much the same fashion by telling the Surefire test-execution plugin to wait for you to attach a debugger to port 5005.

4
1
​
2
mvn test -Dmaven.surefire.debug
3
Listening for transport dt_socket at address: 5005
4
​
Section 12

Source Code Management

Configuring SCM

Your project’s SCM connection can be quickly configured with just three XML tags, which adds significant capabilities to the scm, release, and reactor plugins.

The connection tag is your read-only view of your repository and developerConnection is the writable link. URL is your web-based view of the source.

10
1
​
2
<scm>
3
  <connection>scm:svn:http://myvendor.com/ourrepo/trunk</
4
connection>
5
  <developerConnection>
6
     scm:svn:https://myvendor.com/ourrepo/trunk
7
  </developerConnection>
8
  <url>http://myvendor.com/viewsource.pl</url>
9
</scm>
10
​

Hot Tip

Over 12 SCM systems are supported by Maven. The full list can be viewed at http://docs.codehaus.org/display/SCM/SCM+Matrix

Using the SCM Plugin

The core SCM plugin offers two highly useful goals.

The diff command produces a standard Unix patch file with the extension .diff of the pending (uncommitted) changes on disk that can be emailed or attached to a bug report.

3
1
​
2
mvn scm:diff
3
​

The update-subprojects goal invokes a recursive scm-provider specific update (svn update, git pull) across all the submodules of a multimodule project.

3
1
​
2
mvn scm:update-subprojects
3
​
Section 13

Profiles

Profiles are a means to conditionally turn on portions of Maven configuration, including plugins, pathing and configuration.

The most common uses of profiles are for Windows/Unix platform-specific variations and build-time customization of JAR dependencies based on the use of a specific Weblogic, Websphere or JBoss J2EE vendor.

18
1
​
2
<project>
3
     [...]
4
  <profiles>
5
    <profile>
6
      <id>YourProfile</id>
7
         [...settings, build, plugins etc...]
8
      <dependencies>
9
        <dependency>
10
          <groupId>com.yourcompany</groupId>
11
          <artifactId>yourlib</artifactId>
12
       </dependency>
13
      <dependencies>
14
   </profile>
15
 </profiles>
16
[...]
17
</project>
18
​

Profile Definition Locations

Profiles can be defined in pom.xml, profiles.xml (parallel to the pom.xml), ~/.m2/settings.xml, or $M2_HOME/conf/settings.xml.

Hot Tip

The full Maven Profile reference, including details about when to use each of the profile definition files, can be found at http://maven.apache.org/guides/introduction/introduction-to-profiles.html
Section 14

Profile Activation

Profiles can be activated manually from the command line or through an activation rule (OS, file existence, Maven version, etc.). Profiles are primarily additive, so best practices suggest leaving most off by default, and activating based on specific conditions.

Manual Profile Activation

3
1
​
2
mvn <yourgoal> –P YourProfile
3
​

Automatic Profile Activation

23
1
​
2
<project>
3
     [...]
4
 <profiles>
5
   <profile>
6
     <id>YourProfile</id>
7
     [...settings, build, etc...]
8
  <activation>
9
    <os>
10
      <name>Windows XP</name>
11
      <family>Windows</family>
12
      <arch>x86</arch>
13
      <version>5.1.2600</version>
14
   </os>
15
    <file>
16
       <missing>somefolder/somefile.txt</missing>
17
    </file>
18
  </activation>
19
</profile>
20
</profiles>
21
[...]
22
</project>
23
​
Section 15

Cutting a Release

Maven offers excellent automation for cutting a release of your project. In short, this is a plugin-guided ceremony for verifying that all tests pass, tagging your source code repository, and altering the POMs to reflect a product version increment.

The prepare goal runs the unit tests, continuing only if all pass, then increments the value in the pom <version> tag to a release version, tags the source repository accordingly, and increments the pom version tag back to a SNAPSHOT version.

3
1
​
2
mvn release:prepare
3
​

After a release has been successfully prepared, run the perform goal. This goal checks out the prepared release and deploys it to the POM’s specified remote Maven repository for consumption by other teams and Maven builds.

3
1
​
2
mvn release:perform
3
​
Section 16

Archetypes

An archetype is a powerful template that uses your corporate Java package names and project name in the instantiated project and establishes a baseline of dependencies, with a bonus of basic sample code.

You can leverage public archetypes for quickly starting a project that uses a familiar stack, such as Struts+Spring, or Tapestry+Hibernate. You can also create private archetypes within your company to offer new projects a level of consistent dependencies matching your approved corporate technology stack.

Using an Archetype

The default behavior of the generate goal is to bring up a menu of choices. You are then prompted for various replaceables such as package name and artifactId. Type this command, then answer each question at the command line prompt.

3
1
​
2
mvn archetype:generate
3
​

Creating Archetypes

An archetype can be created from an existing project, using it as the pattern by which to build the template. Run the command from the root of your existing project.

3
1
​
2
mvn archetype:create-from-project
3
​

Archetype Catalogs

The Maven Archetype plugin comes bundled with a default catalog of applications it can create, but other projects on the Internet also publish catalogs. To use an alternate catalog:

3
1
​
2
mvn archetype:generate –DarchetypeCatalog=<catalog>
3
​

A list of the most commonly used catalogs is as follows:

7
1
​
2
local
3
remote
4
http://repo.fusesource.com/maven2
5
http://cocoon.apache.org
6
http://download.java.net/maven/2
7
​
6
1
​
2
http://myfaces.apache.org
3
http://tapestry.formos.com/maven-repository
4
http://scala-tools.org
5
http://www.terracotta.org/download/reflector/maven2/
6
​
Section 17

Reports

Maven has a robust offering of reporting plugins, commonly run with the site generation phase, that evaluate and aggregate information about the project, contributors, it’s source, tests, code coverage, and more.

Adding a Report Plugin

9
1
​
2
&lt:reporting>
3
 &lt:plugins>
4
    &lt:plugin>
5
      &lt:artifactId>maven-javadoc-plugin&lt:/artifactId>
6
    &lt:/plugin>
7
  &lt:/plugins>
8
&lt:/reporting>
9
​

Hot Tip

A list of commonly used reporting plugins can be reviewed here http://maven.apache.org/plugins/

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

Stamping Version Number and Build Time in a Properties File with Maven
related article thumbnail

DZone Article

Installing Maven 3.0.4 on Ubuntu 12.04
related article thumbnail

DZone Article

Offline Resolution of XSDs Using Maven JAXB
related article thumbnail

DZone Article

Tutorial: How to Create a Maven Plugin
related refcard thumbnail

Free DZone Refcard

Platform Engineering Essentials
related refcard thumbnail

Free DZone Refcard

The Essentials of GitOps
related refcard thumbnail

Free DZone Refcard

Continuous Integration Patterns and Anti-Patterns
related refcard thumbnail

Free DZone Refcard

Getting Started With CI/CD Pipeline Security

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: