Jar with dependencies using maven

In the earlier post, though we had dependencies for our jar, we just used them while compiling them. Hence, when we execute our jar, it is required that, they be included in the class-path while executing our jar.

Though, this sounds reasonable enough, there are situations when it becomes tedious to include the dependencies in the class-path every-time you want to run the jar,especially, when there are more than a few dependencies and multiple main-classes. A simpler way is to bundle the other dependent jars in our jar.

Hmmm. This may sound a little off the mark. It is true you cannot bundle the dependent jars in your jar. Albeit, you can include the classes of your dependent jars in your jar. This will solve the problem. Whoa!!! how do i do it?

This can be done pretty easily using Maven in tandem with an assembly.xml. Following are the key points:

a. Use Maven Assembly plugin to assemble the class files in a jar and include their dependencies as well
b. Maven Assembly plugin requires an additional assembly.xml which in turn specifies format e.g. jar and depndency-set
c. Configure the assembly.xml as part of same project and use it from pom.xml using maven assembly plugin
d. Generate one single jar with all dependencies

The sample pom.xml looks like below:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <name>My Blog Reader</name>
        <artifactId>maven-assembly-plugin</artifactId><!--1.Use Maven assembly plugin to assemble the jar-->
            <descriptor>src/assemble/assembly.xml</descriptor><!--2.Assembly configuration-->



The sample assembly.xml is specified below:

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" 
  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">

Useful Links:


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s