Friday, February 26, 2010

Creating an Uber Jar with Maven 2

There may come a time in your life as a developer when you need to create a massive 'uber-jar' for your whole project. What do I mean by Uber-Jar, well, this is a jar that has your project, all its dependencies, AND all it's test files packaged and exploded into one massive jar file, the Uber-Jar. You may be thinking to yourself, why would I ever need to do this? Your thinking is correct, this does sound stupid to include test classes next to regular classes, but consider this use case. You may want to create a jar to run tests on a remote machine, say a dev box, to do performance testing. Ok, enough talk, on with the meat of this thing!

Create a Maven Assembly descriptor for your project to include all dependencies and your test classes. Here is an example:



<assembly>
<id>performance-test</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>${project.build.directory}/test-classes</directory>
<outputDirectory>/</outputDirectory>
</fileSet>
<fileSet>
<directory>${project.build.outputDirectory}</directory>
<outputDirectory>/</outputDirectory>
</fileSet>
</fileSets>
<dependencySets>
<dependencySet>
<unpack>true</unpack>
<scope>runtime</scope>
</dependencySet>
<dependencySet>
<unpack>true</unpack>
<scope>test</scope>
</dependencySet>
</dependencySets>
</assembly>


Ok, so now you have an assembly file. Now we need to instruct maven to run this only when you want it run. For that we need to create a maven build profile. Check it:



<profiles>
<profile>
<id>package.test</id>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>src/main/assembly/performanceTest.xml</descriptor>
</descriptors>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>


Pretty easy so far right? Now we just need to tell maven to run this profile AND generate test classes. Here is a command to do so.

mvn -e clean jar:test-jar assembly:assembly -Ppackage.test 


That's it! You now have a massive jar with tons of dependencies in it including all your source and test files side by side. Enjoy!

No comments:

Post a Comment