Maven commands

Base

Helpful Flags :

 -am,--also-make                        If project list is specified, also
                                        build projects required by the
                                        list
 -amd,--also-make-dependents            If project list is specified, also
                                        build projects that depend on
                                        projects on the list
 -B,--batch-mode                        Run in non-interactive (batch)
                                        mode
 -D,--define <arg>                      Define a system property
 -e,--errors                            Produce execution error messages
 -f,--file <arg>                        Force the use of an alternate POM
                                        file.
 -fae,--fail-at-end                     Only fail the build afterwards;
                                        allow all non-impacted builds to
                                        continue
 -ff,--fail-fast                        Stop at first failure in
                                        reactorized builds
 -fn,--fail-never                       NEVER fail the build, regardless
                                        of project result
 -gs,--global-settings <arg>            Alternate path for the global
                                        settings file
 -h,--help                              Display help information
 -l,--log-file <arg>                    Log file to where all build output
                                        will go.
 -N,--non-recursive                     Do not recurse into sub-projects
 -nsu,--no-snapshot-updates             Suppress SNAPSHOT updates
 -o,--offline                           Work offline
 -P,--activate-profiles <arg>           Comma-delimited list of profiles
                                        to activate
 -pl,--projects <arg>                   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.
 -q,--quiet                             Quiet output - only show errors
 -rf,--resume-from <arg>                Resume reactor from specified
                                        project
 -s,--settings <arg>                    Alternate path for the user
                                        settings file
 -T,--threads <arg>                     Thread count, for instance 2.0C
                                        where C is core multiplied
 -t,--toolchains <arg>                  Alternate path for the user
                                        toolchains file
 -U,--update-snapshots                  Forces a check for updated
                                        releases and snapshots on remote
                                        repositories
 -up,--update-plugins                   Ineffective, only kept for
                                        backward compatibility
 -V,--show-version                      Display version information
                                        WITHOUT stopping build
 -v,--version                           Display version information
 -X,--debug                             Produce execution debug output

Execute a maven goal by specifying the pom (f)ile location :
mvn -f anyPomXml anyGoal

Settings.xml

Generalities

Know the settings and local repository used during a build
mvn -X ...
And look for :

[DEBUG] Reading global settings from /applications/maven3/conf/settings.xml
[DEBUG] Reading user settings from /home/foo/.m2/settings.xml
[DEBUG] Using local repository at /applications/maven3/repository

settings.xml and interpolation/variable resolving

It can be interpolated using the following expressions:
${user.home} and all other system properties (since Maven 3.0)
${env.HOME} etc. for environment variables
But properties defined in profiles within the settings.xml cannot be used for interpolation.

Set a proxy

<proxies>
	<proxy>
		<id>my-proxy</id>
		<active>true</active>
		<protocol>http</protocol>
		<host>foo.com</host>
		<port>8080</port>
		<username>user</username>
		<password>pass</password>
		<nonProxyHosts>*.net.intra|*.</nonProxyHosts>
	</proxy>
</proxies>

Configure repository manager to download and upload artifacts with credentials

Download of maven artifacts from the defined repositories 
– If authentication is required, we may provide credentials in server(s) tag in settings.xml 
The matching between the repository tag in settings.xml and the server tag in settings.xml is done with id and id of each side.

Configure repository manager to deploy artifacts with credentials

Configuration with distributionManagement in pom.xml and server credential cofiguration in settings.xml

That way requires to set some information both in the settings.xml and in the pom.xml and good practice is to set it in a super parent pom to prevent duplication.
– it uploads to the url provided in the distribution management url of the pom.xml.
– it uses provided credentials in server(s) tag in settings.xml.
– The matching between the repository tag in pom.xml/distributionManagement and server tag in settings.xml is done with id and id of each side.


Example :
User project that defines the distribution management to deploy and also configuration credential to download from remote repositories:

    <distributionManagement>
        <snapshotRepository>
            <id>nexus-snapshots</id>
            <url>http://localhost:8072/repository/my-maven-snapshot/</url>
        </snapshotRepository>
        <repository>
            <id>nexus-releases</id>
            <url>http://localhost:8072/repository/maven-releases/</url>
        </repository>
    </distributionManagement>

About settings.xml, we could set it in several ways.
settings.xml with a mirror 

<?xml version="1.0" encoding="UTF-8"?>
 
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
 
  <servers>
    <server>
      <id>nexus-snapshots</id>
      <username>deployment</username>
      <password>deployment</password>
    </server>
    <server>
      <id>nexus-releases</id>
      <username>deployment</username>
      <password>deployment</password>
    </server>
    <!-- to download deps -->
    <server>
      <id>central</id>
      <username>read_user</username>
      <password>read_user</password>
    </server>
 
  </servers>
 
  <mirrors>
    <mirror>
      <id>central</id>
      <name>central</name>
      <url>http://localhost:8072/repository/my-maven-group/</url>
      <mirrorOf>*</mirrorOf>
    </mirror>
  </mirrors>
 
</settings>

Or settings.xml with no mirror.
In that case, we need to override the central repositories with the « central » id and to set it in a profile

<?xml version="1.0" encoding="UTF-8"?>
 
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
 
    <servers>
        <server>
            <id>nexus-snapshots</id>
            <username>deployment</username>
            <password>deployment</password>
        </server>
        <server>
            <id>nexus-releases</id>
            <username>deployment</username>
            <password>deployment</password>
        </server>
        <!-- to download deps -->
        <server>
            <id>central</id>
            <username>read_user</username>
            <password>read_user</password>
        </server>
    </servers>
 
    <profiles>
        <profile>
            <id>nexus</id>
            <repositories>
                <repository>
                    <id>central</id>
                    <name>Maven Central Repo as Nexus</name>
                    <url>http://localhost:8072/repository/my-maven-group/</url>
                </repository>
            </repositories>
            <pluginRepositories>
                <pluginRepository>
                    <id>central</id>
                    <name>Maven Central Plugin Repo as Nexus</name>
                    <url>http://localhost:8072/repository/my-maven-group/</url>
                </pluginRepository>
            </pluginRepositories>
        </profile>
    </profiles>
 
    <activeProfiles>
        <activeProfile>nexus</activeProfile>
    </activeProfiles>
</settings>

Configuration with all information specified in settings.xml

That way overrides the distributionManagement configuration set in the pom.xml.
Further, it even spares the need to add that part in the pom.xml.
Here is the needed configuration in settings.xml :

  <servers>
    <server>
      <id>nexus-snapshots</id>
      <username>deployment</username>
      <password>deployment</password>
    </server>
    <server>
      <id>nexus-releases</id>
      <username>deployment</username>
      <password>deployment</password>
    </server>
   <!-- to download deps -->
    <server>
      <id>central</id>
      <username>read_user</username>
      <password>read_user</password>
    </server>
  </servers>
 
  <mirrors>
    <mirror>
      <id>central</id>
      <name>central</name>
      <url>http://localhost:8072/repository/my-maven-group/</url>
      <mirrorOf>*</mirrorOf>
    </mirror>
  </mirrors>
 
  <profiles>
    <profile>
      <id>nexus</id>
      <properties>
        <altReleaseDeploymentRepository>nexus-releases::http://localhost:8072/repository/maven-releases/</altReleaseDeploymentRepository>
        <altSnapshotDeploymentRepository>nexus-snapshots::http://localhost:8072/repository/my-maven-snapshot/</altSnapshotDeploymentRepository>
      </properties>
    </profile>
  </profiles>

Projects build

Reactor and default build

Multi-modules projects are built by a maven tool called the reactor.
When a maven goal is executed since a multi-module pom, here the main reactor tasks :
– analyzing dependencies between the modules
– computing the modules build order in order to define an order to build the modules in the convenient order.
That means that the declared order of modules in the pom may not be respected by the reactor if that allows the build to be more consistent
– build all modules

Specify modules to build in Reactor

Specify modules to build : -pl or –projects with comma-delimited list of specified modules.
Format for modules : groupId:artifactId or relative path of the module.
Example:
mvn -pl fooGroupId:fooArtifactId,foo/bar/api compile

Specify modules to build along modules that use them:
mvn -pl fooProject,barProject -amd goal

Specify modules to build along modules that these use:
mvn -pl fooProject,barProject -am goal

Build only the current project and not the subprojects

-N or –non-recursive
Example:
mvn -N compile

Maven help plugin

It is used to get relative information about a project or the system.

Effective Pom

Displays the effective POM for the current build :
help:effective-pom

Helpful flags :
Execute with a specific profile enabled : -P fooProfile
help:effective-pom -P fooProfile

To output in comment the origin of described xml elements : -Dverbose
mvn help:effective-pom -Dverbose

Choose another artifact than the current project : -Dartifact
mvn help:effective-pom -Dartifact=groupId:artifactId:version

Effective properties

Evaluates Maven expressions :
mvn help:evaluate -Dexpression=MAVEN_EXPRESSION
Ex: get the current version of the project:
 help:evaluate -Dexpression=project.version

Helpful flags :
Execute with a specific profile enabled : 
mvn help:evaluate -Dexpression=MAVEN_EXPRESSION -P fooProfile

Choose another artifact than the current project :
mvn help:evaluate -Dexpression=MAVEN_EXPRESSION -Dartifact=groupId:artifactId:version

Ouput only the result of the evaluation :
mvn help:evaluate -Dexpression=MAVEN_EXPRESSION -q -DforceStdout

help about profiles and settings

List active profiles for the build :
help:active-profiles

Lists the available profiles under the current project :
help:all-profiles

Display the effective settings for the project, given any profile enhancement and the inheritance of the global settings into the user-level settings :
help:effective-settings

Dependencies Management

Bom

The Bom allows to define a « library » of related artifacts with specific versions.
Its features :
– it is artifact packaged as pom
– don’t require that the maven user project specify the bom as a pom parent
– so don’t benefit from parent inheritance
– don’t include any dependency in the dependencies in the maven user project. It provides them in the dependency management.
It is up to the user project to specify the dependency that it needs (without the version generally).

Basic example 

Bom :

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.4.2</version>
<packaging>pom</packaging>
 
<dependencyManagement>
<dependencies>
  <dependency>
	<groupId>org.apache.activemq</groupId>
	<artifactId>activemq-amqp</artifactId>
	<version>${activemq.version}</version>
  </dependency>
  <! other dependencies .. -->
</dependencyManagement>

User project of that bom :

<groupId>user</groupId>
<artifactId>user</artifactId>
<version>1.0</version>
 
<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-dependencies</artifactId>
			<version>2.4.4</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
		<!-- We can import as many bom as we need -->
		<dependency>
			<groupId>foo</groupId>
			<artifactId>bar</artifactId>
			<version>1.0</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>
 
<dependencies>
	<!-- Now we can import any dependency defined in the boms-->
<dependencies>

Compute version(s) from command line

Get the current version of the pom :
mvn -q -U -Dexpression=project.version -DforceStdout org.apache.maven.plugins:maven-help-plugin:3.2.0:evaluate

Update version(s) from command line

There are two distinct plugins for that : the versions plugin (set goal) and the release plugin (update-versions goal).
These goals look like same but in many ways their behavior is distinct.
In two words : versions:set set versions for dev (snap) or release, it is up to us to decide while release:update-versions sets only the new development version.

Goal : Updating the dev/snapshot version for the current pom, its modules and any dependencies referring to the current pom or its modules.

Case one : for a simple project or a multi-module where all child poms inherit from the parent version
:
mvn --batch-mode release:update-versions -DdevelopmentVersion=1.2.0-SNAPSHOT
or
mvn versions:set -DnewVersion=1.2.0-SNAPSHOT
Differences between the two ways : nothing.

Case two : for a multi-module where all submodules don’t inherit from the parent version but we also want that these to be updated to that new version
:
mvn release:update-versions -DdevelopmentVersion=1.2.0-SNAPSHOT -DautoVersionSubmodules
or
mvn versions:set -DnewVersion=1.2.0-SNAPSHOT -DprocessAllModules
Differences between the two ways : the versions plugin propagates submodule version updates only for submodules that has currently exactly the same version that the aggregator pom while the release plugin update the versions of modules whatever their current version while the version of the dependency match with the version of the project (quite tricky).

Goal : Updating a no-snapshot version for the current pom
A single way :
versions:set -DnewVersion=1.2.0
The same limitations about version alignment for child modules as those discussed for versions:set with a snapshot version apply here too.

Goal : Reverting changes performed by the plugin
Release plugin : no way.
Versions plugin : mvn versions:revert

The dependency plugin : an excellent plugin

Download sources of dependencies of the pom.xml

mvn dependency:sources

To filter the dependencies by artifactIds or groupIds (not work) :

mvn dependency:sources -DincludeArtifactIds=commons-lang3

Dependencies copy

Copy a dependency into a specific directory during a build 

Here I specified the stripVersion argument to true to keep a predictable jar name.

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-dependency-plugin</artifactId>
	<executions>
		<execution>
			<id>copy-my-component-jar</id>
			<phase>prepare-package</phase>
			<goals>
				<goal>copy</goal>
			</goals>
			<configuration>
				<stripVersion>true</stripVersion>
				<artifactItems>
					<artifactItem>
						<groupId>foo.bar</groupId>
						<artifactId>my-component</artifactId>
						<version>1.5.0</version>
						<outputDirectory>${project.build.directory}/anyDir</outputDirectory>
					</artifactItem>
				</artifactItems>
			</configuration>
		</execution>
	</executions>
</plugin>

Copy artifact(s) located in the maven repo (local or remote) to a defined locations Same goal that above but from command line.
The default location of the copy is target/dependency.

For example to copy the org.hibernate:hibernate-core:5.2.14.final pom into target/dependency :

mvn dependency:copy -Dartifact=org.hibernate:hibernate-core:5.2.14.final:pom

To specify the current directory as output directory add the flag : -DoutputDirectory=.

Print the dependency tree of the project

The basic way :

mvn dependency:tree

Beware : the goal is not relevant for dependencies pulled from a bom. Indeed, the bom that pulls them is not visible in the tree.

including only artifacts (it and its declaring) matching to a filter pattern.
The wildcard is optional.
The filter syntax is:

[groupId]:[artifactId]:[type]:[version]

For example :

mvn dependency:tree -Dincludes=velocity:velocity,com.mygroup.*

– excluding artifacts matching to a filter pattern :

mvn dependency:tree -Dexcludes=velocity:velocity,com.mygroup.*

We could even specify both -Dincludes and -Dexcludes.

Force update for all snapshot dependencies during the build:

mvn -U GOAL

Check conflicting dependencies

With the maven-enforcer-plugin.
Ex where we bind the plugin execution to the maven validate phase :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-enforcer-plugin</artifactId>
    <version>3.0.0-M3</version>
    <executions>
      <execution>
        <id>default-cli</id>
        <phase>validate</phase>
        <goals>
          <goal>enforce</goal>
        </goals>                            
        <configuration>
          <rules>
            <banDuplicateClasses>
              <ignoreClasses>
                <!-- example of ignoring one specific class -->
                <ignoreClass>com.xyz.i18n.Messages</ignoreClass>
 
                <!-- example of ignoring with wildcards -->
                <!-- <ignoreClass>org.apache.commons.logging.*</ignoreClass>-->
              </ignoreClasses>
              <scopes>
                  <scope>compile</scope>
                  <scope>provided</scope>
              </scopes>
              <findAllDuplicates>true</findAllDuplicates>
              <ignoreWhenIdentical>true</ignoreWhenIdentical>
            </banDuplicateClasses>
          </rules>
          <fail>true</fail>
        </configuration>
      </execution>
    </executions>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>extra-enforcer-rules</artifactId>
        <version>1.3</version>
      </dependency>
    </dependencies>
 </plugin>

We could so execute mvn validate or any further phase to perform the validation.
The alternative is executing directly : mvn enforcer:enforce

Pass JVM arguments/options

Globally (all projects, all phases)

export MAVEN_OPTS="..."

For a specific project (since maven 3.3.1)

Edit a file with the jvm options in : ${maven.projectBasedir}/.mvn/jvm.config

In Unit test

mvn test -DargLine="-Djdk.serialFilter=* -Dother=foo"

In Suite/custom runner

The previous way not with suite and custom runner. In that case, the classic way may work :

mvn test -Djdk.serialFilter=* -Dother=foo

Build issues

Concurrent builds backed on the same local repository.
Maven client uses pooled connections with wagon by default and it also « might » re-use connections.
On common environments where there is a single maven client instance that uses a local repository, no issue. But if you multiple maven client instances backed on the same local repository (which may occur in CD/CI envs), we could get freezes during maven dependency resolutions.
How to fix :
Disable the caching connections. 
We could do that by running Maven with the flags :
-Dhttp.keepAlive=false -Dmaven.wagon.http.pool=false

Build failure but no details
Since maven compiler 3.0, Maven compiler can now use javax.tools if available in the jdk (it is the case for Java 9+ versions).
That may produce build failure but with no details about the error such as :

Exception in thread "main" java.lang.AssertionError
at jdk.compiler/com.sun.tools.javac.util.Assert.error(Assert.java:155)
....

To know build errors cause, we could disable javax.tools and force the javac compiler use instead of by adding the <forceJavacCompilerUse>true</forceJavacCompilerUse> property in the maven compiler plugin.

Configure maven-sure-plugin to include tests to run

That is helpful in cases of tests that have as fixture a suite test class and tests class. Makes sense to test components that rely on or run a suite test.
To test such a component, we may need to define a suite that runs a set of test classes such as :

@SuiteClasses(value = {FooTest.class, BarTest.class, FooBarTest.class}
public class FooSuiteForTesting{...}

Here FooTest, BarTest and FooBarTest are class fixtures used in our unit test.
So as usually we find inside a package in the src/test/java test source directory.
If we don’t care about it, tests executed inside the FooSuiteForTesting suite will also be executed as single class tests when we run mvn test.
We don’t want that. To prevent that, we will define the suite and test fixtures for the suite inside a dedicated package such as :

com.foo.suite.FooSuiteForTesting
com.foo.suite.FooTest
com.foo.suite.BarTest
com.foo.suite.FooBarTest

And if we have them, we will locate tests that don’t run inside the suite, in the parent folder such as :

com.foo.AnyTest
com.foo.SomeTest

At last, here the required surefire maven plugin configuration :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <includes>
            <include>**/foo/suite/FooSuiteTest.java</include>
            <include>**/foo/*Test.java</include>
        </includes>
    </configuration>
</plugin>

Skip both test compilation and test execution

mvn -Dmaven.test.skip package

Compile tests but don’t execute them

mvn -DskipTest package

Run a specific test class

mvn -Dtest=TestClass test

We could even specify a pattern

mvn -Dtest=*Test test

The qualified class is not mandatory

Run tests matching to to a package

mvn -Dtest="foo.bar.**" test

 

Run a specific method of a test class

mvn -Dtest=TestClass#fooMethod test


Run some specific methods of a test class

mvn -Dtest=TestClass#fooMethod+barMethod test


Run mvn in debug mode

With any maven goal such as exec:java

Most reliable way : exporting the MAVEN_OPTS argument with the Xdebug flags such as :
export MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8888"

Standard surefire

With the default conf (default port with 5005 among others) :

mvn test -Dmaven.surefire.debug

With specific conf :

mvn test -Dmaven.surefire.debug="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8888 -Xnoagent -Djava.compiler=NONE"

With a specific test (with breakpoints in IDE) :

mvn test -Dmaven.surefire.debug -Dtest=simpleClassNameOrFullyQualifiedClassName

Standard failsafe

With the default conf (default port with ??? among others) :

mvn test -Dmaven.failsafe.debug

With specific conf : todo

Show whole stacktrace in surefire output

By default, surefire output trims the stacktraces.
To show it entirely we need to set the trimStackTrace parameter of the plugin to true.
We could do that dynamically in commandline via the user property trimStackTrace such as :  mvn test -DtrimStackTrace=false
Or statically, by adding it in the plugin configuration of the pom.xml :

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-surefire-plugin</artifactId>
	<configuration>
		   <trimStackTrace>false</trimStackTrace>
	</configuration>
</plugin>

Fork mode for running test

By default, fork mode for tests execution is enabled (forkCount parameter to 1). We can disable it by valuing forkCount to 0 such as :

            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.21.0</version>
                <configuration>
                    <forkCount>0</forkCount>
                </configuration>
            </plugin>

Beware : some test runners may have as prerequisites to use fork for tests, it means that test executions may fail when we disable it.
For example that is the case for Cucumber 2.X version (2.1 to 2.4 at least).

Run a main class without packaging it

Compile the project first, then execute that:
mvn compile exec:java -Dexec.mainClass=foo.MyApp
– To pass program args, we specify-Dexec.args="..." :
Example :
mvn compile exec:java -Dexec.mainClass=foo.FooApp -Dexec.args="--user 'foo_user' --password 'foo_pass'"
– About programs args :
If these contain expandable chars such as ! char, we could prevent their expansion by extracting the string that contains that or these into a variable by using the single quote syntax :
export pass='foo_pass!yes'
mvn compile exec:java -Dexec.mainClass=foo.FooApp -Dexec.args="--user 'foo_user' --password '$pass'"

Exclusion of dependencies

Mark a specific dependency as « provided » wherever it comes from

Simple but limited :
– It is a soft exclusion because the dependency is marked only as « provided ». It means that is not packaged in the application but that is still available at compile and test time.
– It requires to specify the exact version of the artifact. It means that if the version changes over the time, the exclusion will not work any longer.
Ex : add it in the pom that packages the application to mark dom4j:dom4j:2.1.3 as provided.

<dependencies>
    <dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>2.1.3</version>
    <scope>provided</scope>
 </dependency>    
</dependencies>

Exclude a dependency pulled by a dependency or one of these children dependencies

Powerful as it excludes the dependency from every scope (test, compilation, runtime).
But it requires to identify which dependency pulls directly or indirectly (if done by a children dependencies) the dependency we want to exclude.
Suppose that we want to exclude dom4j:dom4j dependency in the pom.xml of our bar project that builds a application(jar)
Case 1  : dom4j is defined in the foo:foo child dependency that bar:bar declares :

bar:bar
|
+- foo:foo:1.0
    |
    -dom4j:dom4j:...
    -common:common-lang:...
    -...

Case 2 : dom4j is not directly defined in the foo:foo dependency but in foo:super-foo, one of these children dependencies:

bar:bar
|
+- foo:foo:1.0
    |
    - common:common-lang
    +- foo:super-foo
          |
          - dom4j:dom4j:...

In any case we could exclude dom4j of the bar project in that way :

<dependency>
	<groupId>foo</groupId>
	<artifactId>foo</artifactId>
	<version>1.0</version>
	<exclusions>
		<exclusion>
			<groupId>dom4j</groupId>
			<artifactId>dom4j</artifactId> 
		</exclusion>
	</exclusions>
</dependency>

Exclude dependency(ies) from the test classpath

Add the groupId:artifactId dependencies to exclude such as :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
            <classpathDependencyExcludes>
                <classpathDependencyExclude>dom4j:dom4j</classpathDependencyExclude>
                <classpathDependencyExclude>groupId:artifactId</classpathDependencyExclude>
             </classpathDependencyExcludes>
    </configuration>
</plugin>

Create a fat jar (without spring boot)

Execute mvn clean package with a pom.xml :

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-assembly-plugin</artifactId>
	<configuration>
		<archive>
			<manifest>
				<mainClass>davidxxx.MyMainApp</mainClass>
				<!-- optional
				<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
				<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
				-->
			</manifest>
		</archive>
		<descriptorRefs>
			<descriptorRef>jar-with-dependencies</descriptorRef>
		</descriptorRefs>
	</configuration>
	<executions>
		<execution>
			<id>my-assembly</id>
			<phase>package</phase>
			<goals>
				<goal>single</goal>
			</goals>
		</execution>
	</executions>
</plugin>

Deploy artifacts

Deploy a jar with its pom

  mvn org.apache.maven.plugins:maven-deploy-plugin:3.0.0-M1:deploy-file \
    -Durl=http://nexus.foo.com/content/repositories/foo-releases \
    -DrepositoryId=FOO_REPOID_IN_SETTINGSXML \
    -Dfile=app-1.0.0.jar \
    -DpomFile=app-1.0.0.pom

Deploy a jar or any packaging (zip, tar…) without its pom

mvn org.apache.maven.plugins:maven-deploy-plugin:3.0.0-M1:deploy-file \
    -Durl=http://nexus.foo.com/content/repositories/foo-releases \
    -DrepositoryId=FOO_REPOID_IN_SETTINGSXML \
    -Dfile=app-1.0.0.jar \
     ...

About that way, if we don’t specify the pomFile argument but that the archive (jar, zip…) contains a pom.xml in META-INF\maven\... folder, it will be uploaded as the pom.xml of the deployed artifact .

Common problems

Third party maven plugins

Problem :
Execute a third-party maven plugin without group prefix such as :
mvn versions:set -DnewVersion=2.0.0
fails early with a message like :

[ERROR] No plugin found for prefix 'versions' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories...

Solutions:
– specify the whole group/artifact name of the plugin :
mvn org.codehaus.mojo:versions-maven-plugin:set -DnewVersion=2.0.0

Ce contenu a été publié dans Non classé. Vous pouvez le mettre en favoris avec ce permalien.

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *