Wednesday, May 12, 2010

How to Include All the Dependencies into a Single JAR using Maven

A lot of times, we need to create a single JAR file with all the dependencies into a single JAR. The advantage of this approach is to make it easier to distribute the JAR. This approach has one problem, though, that is when we need to update some of the dependencies inside that JAR, we need to unjar the JAR first, update the dependencies and jar it back. Nevertheless, this approach is commonly used for desktop applications to create an executable JAR. Below is how to package the dependencies into a single JAR using Maven.

Add these lines in pom.xml.
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
    </configuration>
    <executions>
        <execution>
            <id>jar-with-dependencies</id>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>

We use Maven Assembly plugin here. We can include the 'single' goal from maven-assembly-plugin into the 'package' phase. So rather than typing 'mvn assembly:assembly', we can just type 'mvn package' and all the dependencies will be inside a single JAR.

To build an executable JAR, we need an additional step to include the Main-Class in the MANIFEST.MF. All we need to do is to add these lines in the pom.xml as shown below.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
    </configuration>
    <executions>
        <execution>
            <archive>
                <manifest>
                    <mainClass>myproject.Main</mainClass>
                </manifest>
            </archive>
            <id>jar-with-dependencies</id>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>

No comments:

Post a Comment