Maven Include Dependencies in JAR Artifact
Internal
Overview
There are situations when we want to extract some of the dependencies and bundle them with the JAR artifact, merged with the artifact classes. This is done using the jar plugin and the dependency plugin together, as described below.
Configure the Maven dependency plugin to unpack dependencies, or just some of them, in the directory that will be archived by the jar plugin:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <id>unpack-some-dependencies</id> <phase>prepare-package</phase> <goals> <goal>unpack-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/classes</outputDirectory> <includes>**/SimpleStateless.class</includes> <overWriteReleases>false</overWriteReleases> <overWriteSnapshots>false</overWriteSnapshots> <overWriteIfNewer>true</overWriteIfNewer> </configuration> </execution> </executions> </plugin>
Essential bits of configuration are the following:
- the "unpack-dependencies" goal, which tells the plugin the extract classes from the transitive dependency tree.
- outputDirectory "${project.build.directory}/classes" is the directory picked up by the jar plugin.
- <includes>**/SimpleStateless.class</includes> the filter that selects the classes we want in the JAR artifact.
Overwriting Problem
The dependency plugin usually executes at "prepare-package" phase, and thus it may overwrite project's own resources with the same name, which are copied in the same output directory by the resources plugin, at a earlier phase "process-resources" and "process-test-resources". This issue can be fixed by explicitly running the resources plugin at the "prepare-package" phase for the conflicting project resources we want in the final artifact.