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:
validate: validate the project and its information.compile: compile the source code.test: compile the test code and run the unit tests.package: package the compiled code into a JAR, WAR or other archive.verify: run checks on the results of integration tests.install: install the package from thepackagephase into the local repository (~/.m2/repository).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:
brew install --cask temurin@17cd "$(brew --prefix)/opt"ln -s /Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home openjdkbrew install --ignore-dependencies mavenbrew --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:
mvn exec:exec -DcustomerId=1234 -Doutcome=REJECTED -DserviceUrl=http://localhost:8080/services/soapSkip tests, GPG signing and Javadoc
For a quick local build, skip the slow or credential-dependent steps:
mvn clean install -DskipTests -Dgpg.skip -Dmaven.javadoc.skip=true-DskipTestscompiles the tests but does not run them. Use-Dmaven.test.skip=trueto skip compiling them as well.-Dgpg.skipskips signing by themaven-gpg-plugin.-Dmaven.javadoc.skip=trueskips Javadoc generation by themaven-javadoc-plugin.
Show the dependency tree
To print every dependency, including transitive ones, as a tree:
mvn dependency:treeIn 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:
mvn versions:display-dependency-updatesCreate 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:
mvn archetype:create-from-projectThis generates the archetype under target/generated-sources/archetype. Its folder structure looks like this:
cd target/generated-sources/archetypetree -d.└── src ├── main │ └── resources │ ├── META-INF │ │ └── maven │ └── archetype-resources │ └── src │ └── main │ ├── java │ └── webapp │ └── WEB-INF └── test └── resources └── projects └── basicIf 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
- Right-click the Dependencies folder in the Projects view and add a dependency.
- Enter a
groupId,artifactIdandversionfor the JAR. - The dependency is added to
pom.xmland appears under the Libraries node of the project. - Right-click the library node, choose Manually install artifact and enter the path to the JAR.
- 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:
mvn -DartifactId=<artifact-id> -DgroupId=<group-id> -Dversion=<version> -Dpackaging=jar -Dfile=<path-to-jar> -DgeneratePom=false install:install-fileWith 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:
<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:
<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:
<?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:
gpg --gen-keyList the available keys to find the key ID:
gpg --list-keysPublish the public key to a keyserver so that others can verify your signatures:
gpg --keyserver hkp://keys.openpgp.org --send-keys <key-id>Then check the configuration with a build that runs the verify phase:
mvn clean verifySign only release builds
To avoid signing on every build, put the plugin in a profile that is activated by a property:
<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:
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:
GPG_TTY=$(tty)export GPG_TTYThen reload the file in the current shell:
source ~/.zshrcError: gpg: keyserver receive failed: No route to host
The keyserver is unreachable. List the keyservers GPG knows about:
gpg-connect-agent --dirmngr 'keyserver --hosttable'Then send or receive the key through a server that responds:
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:
git config user.signingkey 35F5FFB2Or set it globally to use the same key in every repository:
git config --global user.signingkey 35F5FFB2Replace 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:
mvn -V -B -s settings.xml deploy-Vprints the Maven and Java versions at the start of the build.-Bruns in batch mode, which suppresses the download progress output for each artifact.-s settings.xmluses 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:
<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:
mvn clean package glassfish:deployNote: 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:
<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:
mvn clean wildfly:deployVersion 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:
<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:
mvn exec:exec -PproductionThe 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:
<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
- Introduction to the build lifecycle (Apache Maven)
- archetype:create-from-project goal (Apache Maven)
- Creating Maven archetypes: a tutorial
- install:install-file goal (Apache Maven)
- Install a local JAR with Maven (Baeldung)
- Inject Maven project information into a Java application
- Maven GPG Plugin (Apache Maven)
- GPG requirements for Maven Central (Sonatype)
- Releasing a deployment to Maven Central (Sonatype)
- OSSRH sunset announcement (Sonatype)
- Publishing with Maven through the Central Publisher Portal (Sonatype)
- Maven release to Nexus (Baeldung)
- WildFly Maven Plugin documentation
- Exec Maven Plugin (MojoHaus)
- Deleting additional files with the Maven Clean Plugin
- versions:display-dependency-updates goal (MojoHaus)