Problem:
How to use Maven to package a project with dependencies? The solution is to use maven-assembly-plugin as in the following example.
Solution:
Here we’ll use very simple Maven project with compile dependency on Apache Commons Lang3 library. Packaging of the bundle is done by maven-assembly-plugin according to a configuration. Fortunately, the plugin comes with a couple of ready to use configurations, one of which is jar-with-dependencies:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.farenda.java</groupId> <artifactId>solved</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.5.5</version> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> </plugins> </build> </project>
Sample Java code using our dependency (Apache Commons Lang3):
package com.farenda.java; import org.apache.commons.lang3.LocaleUtils; import java.util.Locale; public class JavaSolved { public static void main(String[] args) { for (Locale locale : LocaleUtils.availableLocaleSet()) { System.out.printf("Country: %s, language: %s%n", locale.getCountry(), locale.getLanguage()); } } }
Now, running mvn assembly:assembly command will tell Maven to run the assembly plugin with configuration from the pom.xml.
All project classes with dependencies have been packed into target/solved-0.0.1-SNAPSHOT-jar-with-dependencies.jar. Here are sample entries that confirm correct packaging:
-rw-r--r-- 1067 21-Aug-2015 18:16:20 com/farenda/java/JavaSolved.class -rw-r--r-- 7004 3-Apr-2015 14:30:26 org/apache/commons/lang3/AnnotationUtils.class -rw-r--r-- 246 3-Apr-2015 14:30:26 org/apache/commons/lang3/builder/Builder.class
As you can see dependent JAR has been unpacked and repackaged with project code. Such single JAR is easier to distribute than whole bunch.