Using Maven2 to Build a Single Stand-Alone Jar File

Move along, nothing fun to see here, just some help for random Googlers about a grungy maven problem I was having last night.

I’m working on a project that uses Maven2 and I needed a way to package my code plus all dependencies into a single jar file. This would let me distribute it as a self-contained, executable jar rather than something that needs to be installed. It took me a surprisingly long time to stumble onto the answer, so hopefully this will shorten the search for some other people.

In ant it’s fairly straightforward. The jar task can include a zipgroupfileset nested element like so:

<target name=”jar-dep” depends=”compile”>
<jar jarfile = ”${deployment.dir}/${jar-name}.jar”
basedir = ”${build.dest}”
manifest = ”MANIFEST.MF”>
<zipgroupfileset dir=”${jars.dir}”>
<include name=”**/*.jar”/>
</zipgroupfileset>
</jar>
</target>

I found a great blog post, Building one big fat jar file, that warned me off of the Uberjar plugin. But, the javaapp plugin he suggests instead are Maven 1.x only.

The “real” way to create a bundled jar file in maven2 is to use the maven-assembly-plugin which, true to maven’s promise, slots right in and Just Works:

<build>

<plugins>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.1</version>
<configuration>
<descriptors>
<descriptor>jar-with-dependencies.xml</descriptor>
</descriptors>
<finalName>final_name</finalName>
<outputDirectory>target</outputDirectory>
<workDirectory>target/assembly/work</workDirectory>
<archive>
<manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
</plugins>
</build>

And the descriptor that allows a single jar file to be built is conveniently provided:

<assembly>
<id>jar-with-dependencies</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>target/classes</directory>
<outputDirectory>target</outputDirectory>
</fileSet>
</fileSets>
<dependencySets>
<dependencySet>
<outputDirectory>/</outputDirectory>
<unpack>true</unpack>
<scope>runtime</scope>
</dependencySet>
</dependencySets>
</assembly>

Viewing 5 Comments

 

Trackbacks

(Trackback URL)

close Reblog this comment
blog comments powered by Disqus
© 2009 Synthesis Studios. All rights reserved. Terms & Conditions | Privacy Policy | Accessibility