Skip to content

Maven

Maven reference: build lifecycle, properties, skipping tests, archetypes, local JARs, GPG signing, deploy plugins and dependency checks.

9 min readUpdated

Apache Maven builds Java projects from a declarative pom.xml: it resolves dependencies, runs a fixed lifecycle of build phases and calls plugins for each phase. This note collects practical recipes: the lifecycle, passing properties, skipping steps, creating archetypes, installing local JARs, signing artifacts with GPG, deploying to application servers and checking dependencies.

Build lifecycle

The default lifecycle runs these main phases in order:

  1. validate: validate the project and its information.
  2. compile: compile the source code.
  3. test: compile the test code and run the unit tests.
  4. package: package the compiled code into a JAR, WAR or other archive.
  5. verify: run checks on the results of integration tests.
  6. install: install the package from the package phase into the local repository (~/.m2/repository).
  7. deploy: copy the package to a remote repository to share it with other developers.

When you run mvn <phase>, Maven runs every phase from validate up to and including the phase you name. For example, mvn install also compiles, tests, packages and verifies.

Install Maven with Homebrew but without OpenJDK

On macOS, the Homebrew maven formula pulls in Homebrew’s openjdk. If you already use another JDK, such as Eclipse Temurin, you can install Maven without that dependency and link your JDK in its place:

Terminal window
brew install --cask temurin@17
cd "$(brew --prefix)/opt"
ln -s /Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home openjdk
brew install --ignore-dependencies maven

brew --prefix is /opt/homebrew on Apple Silicon and /usr/local on Intel Macs. --ignore-dependencies is an unsupported Homebrew option, so Homebrew may warn about it. Older Homebrew versions named the cask temurin17.

Pass or override properties

The -D option sets a property for the build. It overrides a property of the same name defined in the POM or in an active profile of ~/.m2/settings.xml, and plugins can read it as a parameter:

Terminal window
mvn exec:exec -DcustomerId=1234 -Doutcome=REJECTED -DserviceUrl=http://localhost:8080/services/soap

Skip tests, GPG signing and Javadoc

For a quick local build, skip the slow or credential-dependent steps:

Terminal window
mvn clean install -DskipTests -Dgpg.skip -Dmaven.javadoc.skip=true
  • -DskipTests compiles the tests but does not run them. Use -Dmaven.test.skip=true to skip compiling them as well.
  • -Dgpg.skip skips signing by the maven-gpg-plugin.
  • -Dmaven.javadoc.skip=true skips Javadoc generation by the maven-javadoc-plugin.

Show the dependency tree

To print every dependency, including transitive ones, as a tree:

Terminal window
mvn dependency:tree

In NetBeans, open pom.xml and switch to the Graph tab to see the same information as a dependency graph.

Check for newer dependency versions

The Versions Maven Plugin lists dependencies that have newer versions in the configured repositories:

Terminal window
mvn versions:display-dependency-updates

Create an archetype from a project

An archetype is a project template. You can turn an existing project into one and then generate new projects from it.

Generate the base archetype

Change into the project directory (for a multi-module project, the parent or aggregator project) and run:

Terminal window
mvn archetype:create-from-project

This generates the archetype under target/generated-sources/archetype. Its folder structure looks like this:

Terminal window
cd target/generated-sources/archetype
tree -d
.
└── src
├── main
│ └── resources
│ ├── META-INF
│ │ └── maven
│ └── archetype-resources
│ └── src
│ └── main
│ ├── java
│ └── webapp
│ └── WEB-INF
└── test
└── resources
└── projects
└── basic

If the generated archetype contains a target sub-tree, discard it by running mvn clean inside target/generated-sources/archetype. Do not run mvn clean in the original project at this point: that would delete the generated archetype. Run mvn install in the archetype directory to install it into your local repository.

Adjust the archetype

Edit the files under archetype-resources and use these placeholders where the new project’s name must appear:

  • ${rootArtifactId} inside files: variables, methods, comments and other text that depend on the project name.
  • __rootArtifactId__ in file and folder names.

Add a local JAR to a project

In NetBeans

  1. Right-click the Dependencies folder in the Projects view and add a dependency.
  2. Enter a groupId, artifactId and version for the JAR.
  3. The dependency is added to pom.xml and appears under the Libraries node of the project.
  4. Right-click the library node, choose Manually install artifact and enter the path to the JAR.
  5. The JAR is installed into the local Maven repository with the coordinates from step 2.

Behind the scenes, NetBeans runs this command, which you can also run yourself:

Terminal window
mvn -DartifactId=<artifact-id> -DgroupId=<group-id> -Dversion=<version> -Dpackaging=jar -Dfile=<path-to-jar> -DgeneratePom=false install:install-file

With the maven-install-plugin

To install the JAR automatically on every build, bind the install-file goal to the validate phase. This example installs barcode4j-light.jar from a dependencies folder in the project:

pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
<configuration>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j-light</artifactId>
<version>2.1</version>
<packaging>jar</packaging>
<file>${basedir}/dependencies/barcode4j-light.jar</file>
<generatePom>true</generatePom>
</configuration>
<executions>
<execution>
<id>install-jar-lib</id>
<goals>
<goal>install-file</goal>
</goals>
<phase>validate</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>

Then declare net.sf.barcode4j:barcode4j-light:2.1 as a normal dependency. This configuration was written for version 2.5.2 of the plugin.

Inject project information into a Java application

Values such as the project version or build time can be written into a resource file with Maven resource filtering and read at runtime. See Inject Maven project information into a Java application for a worked example.

Sign artifacts with GPG

Maven Central requires every published artifact to be signed with GPG. The maven-gpg-plugin signs the artifacts in the verify phase:

pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

Version 1.6 is the version this note was written with; check the plugin page for the current release.

Provide the passphrase in settings.xml

Maven reads two settings files: the global one in the Maven installation (conf/settings.xml) and the optional user one in ~/.m2/settings.xml. Settings in the user file take precedence over the global ones.

The GPG plugin looks up its passphrase in the server entry with the id gpg.passphrase:

~/.m2/settings.xml
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
<servers>
<server>
<id>gpg.passphrase</id>
<passphrase>P@assphrase123</passphrase>
</server>
</servers>
</settings>

Create and publish a key

If you do not have a key yet, generate a key pair:

Terminal window
gpg --gen-key

List the available keys to find the key ID:

Terminal window
gpg --list-keys

Publish the public key to a keyserver so that others can verify your signatures:

Terminal window
gpg --keyserver hkp://keys.openpgp.org --send-keys <key-id>

Then check the configuration with a build that runs the verify phase:

Terminal window
mvn clean verify

Sign only release builds

To avoid signing on every build, put the plugin in a profile that is activated by a property:

pom.xml
<profiles>
<profile>
<id>release-sign-artifacts</id>
<activation>
<property>
<name>performRelease</name>
<value>true</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>

When you make a release, set the property on the command line:

Terminal window
mvn -DperformRelease=true ...

Error: gpg: signing failed: Inappropriate ioctl for device

GPG cannot find the terminal to ask for the passphrase. Add these lines to ~/.bash_profile or ~/.zshrc:

Terminal window
GPG_TTY=$(tty)
export GPG_TTY

Then reload the file in the current shell:

Terminal window
source ~/.zshrc

Error: gpg: keyserver receive failed: No route to host

The keyserver is unreachable. List the keyservers GPG knows about:

Terminal window
gpg-connect-agent --dirmngr 'keyserver --hosttable'

Then send or receive the key through a server that responds:

Terminal window
gpg --keyserver hkp://keys.openpgp.org --send-keys <key-id>
gpg --keyserver hkp://keys.openpgp.org --recv-keys <key-id>
gpg --keyserver hkp://pgp.mit.edu --send-keys <key-id>
gpg --keyserver hkp://pgp.mit.edu --recv-keys <key-id>

Error: git commit signing failed: secret key not available

The same GPG key can sign Git commits, but Git must be told which key to use. Configure it for the current repository:

Terminal window
git config user.signingkey 35F5FFB2

Or set it globally to use the same key in every repository:

Terminal window
git config --global user.signingkey 35F5FFB2

Replace 35F5FFB2 with your own key ID from gpg --list-keys.

Deploy to Maven Central with mvn deploy

mvn deploy runs the whole build lifecycle. With the source, Javadoc and GPG plugins configured in the POM, as Maven Central requires, it:

  • compiles the main and test Java code
  • runs the tests
  • creates a JAR with the compiled code and resources
  • creates a JAR with the source code
  • generates the Javadoc HTML files and a JAR containing them
  • signs all artifacts with GPG
  • installs them into the local repository
  • uploads them to the remote repository configured in distributionManagement

The version number decides the target. A version ending in -SNAPSHOT goes to the snapshot repository. Any other version is a release: with the OSSRH (Sonatype Nexus) setup it went to a staging repository, where you verified the components and released them to the Central Repository.

Note: Sonatype shut down OSSRH on 30 June 2025. New and migrated namespaces publish through the Central Publisher Portal; see the references below.

In a CI pipeline (this note used Bitbucket Pipelines), the invocation was:

Terminal window
mvn -V -B -s settings.xml deploy
  • -V prints the Maven and Java versions at the start of the build.
  • -B runs in batch mode, which suppresses the download progress output for each artifact.
  • -s settings.xml uses a settings file from the repository that holds the required credentials, usually filled from CI variables.

Deploy to GlassFish with maven-glassfish-plugin

To deploy a WAR to a GlassFish domain from Maven, add the plugin to pom.xml. The glassfish.home and glassfish.passfile properties come from a profile in ~/.m2/settings.xml, so the credentials stay out of the POM:

pom.xml
<build>
<plugins>
<plugin>
<groupId>org.glassfish.maven.plugin</groupId>
<artifactId>maven-glassfish-plugin</artifactId>
<version>2.1</version>
<configuration>
<glassfishDirectory>${glassfish.home}</glassfishDirectory>
<user>admin</user>
<!--<adminPassword>${glassfish.adminPassword}</adminPassword>-->
<passwordFile>${glassfish.passfile}</passwordFile>
<domain>
<name>domain1</name>
<httpPort>8080</httpPort>
<adminPort>4848</adminPort>
</domain>
<components>
<component>
<name>${project.artifactId}</name>
<artifact>target/${project.build.finalName}.war</artifact>
</component>
</components>
<debug>true</debug>
<terse>false</terse>
<echo>true</echo>
</configuration>
</plugin>
</plugins>
</build>

Then build and deploy:

Terminal window
mvn clean package glassfish:deploy

Note: version 2.1 of this plugin is old and no longer maintained. Check that it still works with your GlassFish version.

Deploy to WildFly with wildfly-maven-plugin

Add the plugin to pom.xml:

pom.xml
<build>
<plugins>
<plugin>
<groupId>org.wildfly.plugins</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>2.0.0.Final</version>
</plugin>
</plugins>
</build>

Then deploy the application to a running WildFly server:

Terminal window
mvn clean wildfly:deploy

Version 2.0.0.Final is the version this note was written with; see the plugin documentation for the current one.

Run a command with exec-maven-plugin

The exec-maven-plugin runs an external program as part of the build. This example backs up a MySQL database with mysqldump; the database.* and env.name properties come from a Maven profile such as production:

pom.xml
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>default-cli</id>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>/usr/bin/mysqldump</executable>
<workingDirectory>/tmp/${database.schema}</workingDirectory>
<commandlineArgs>${database.schema} --host ${database.host} --user=${database.username} --password=${database.password} --result-file=${env.name}_${database.schema}_backup.sql</commandlineArgs>
</configuration>
</plugin>
</plugins>
</build>

Run it with the profile that defines the properties:

Terminal window
mvn exec:exec -Pproduction

The execution id default-cli makes this configuration apply when you call exec:exec directly from the command line.

Delete extra files with maven-clean-plugin

By default mvn clean deletes only the target directory. To delete other files too, list them as filesets. This example deletes the data directory and all .dmg, .tmp and .log files in the project, except two log files:

pom.xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<filesets>
<fileset>
<directory>${basedir}/data</directory>
</fileset>
<fileset>
<directory>${basedir}/</directory>
<includes>
<include>**/*.dmg</include>
<include>**/*.tmp</include>
<include>**/*.log</include>
</includes>
<excludes>
<exclude>**/important.log</exclude>
<exclude>**/another-important.log</exclude>
</excludes>
<followSymlinks>false</followSymlinks>
</fileset>
</filesets>
</configuration>
</plugin>

followSymlinks set to false keeps the plugin from deleting files outside the project through symbolic links.

References

Related notes

2 min read

ngrok

Expose a local web server on a public HTTPS address with ngrok, for webhook testing, demos and testing on real devices.

  • Developer Tools
2 min read

NetBeans

Build Apache NetBeans from source, clear the Recent Projects list and choose the JDK the IDE runs on.

  • Developer Tools
4 min read

Jakarta EE

Jakarta EE 10 and 11: component versions, deployment descriptor headers, Faces namespaces and a multi-module project layout.

  • Java & Jakarta EE

Type to search the whole site.