Including dependencies in a jar with Maven
To include dependencies in a JAR file with Maven, you can use the maven-assembly-plugin to create an assembly that includes all the dependencies of your project.
To include dependencies in a JAR file with Maven, you can use the maven-assembly-plugin to create an assembly that includes all the dependencies of your project.
First, add the maven-assembly-plugin to your pom.xml file and configure it to use an external descriptor:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<descriptors>
<descriptor>src/main/assembly/assembly.xml</descriptor>
</descriptors>
</configuration>
</plugin>
</plugins>
</build>Next, create the src/main/assembly/assembly.xml file to define how dependencies should be packaged:
<!-- src/main/assembly/assembly.xml -->
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd">
<id>project</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>/</outputDirectory>
<useProjectArtifact>true</useProjectArtifact>
<unpack>true</unpack>
</dependencySet>
</dependencySets>
</assembly>Finally, run the assembly:single goal of the maven-assembly-plugin to create the JAR file with dependencies:
mvn assembly:singleThis will create the JAR file in the target directory (typically named project-with-dependencies-project.jar based on your <finalName> and the <id> in the assembly descriptor), which includes all the dependencies of your project.
Note that assembly:single processes the current project. If you need to bundle dependencies for multiple modules or prefer better dependency conflict resolution, consider using the maven-shade-plugin instead.
To make the resulting JAR executable, ensure your pom.xml specifies the main class in the maven-jar-plugin configuration, or use the maven-shade-plugin to automatically set the Main-Class manifest attribute.