Archive for February 2013

Packaging jars using maven   Leave a comment

In this post we shall learn how to package jars using maven. We know that we can easily package our code into wars, but what if we want to build a standalone application that depends on different jars. We can use the maven assembly plugin in order to build a jar and also a jar with all it’s dependencies.

Here are the steps and we shall use the ‘GitTest’ project that depends on ‘jarproject’ in order to demonstrate this:

  1. Enter the following xml snippet into plugings section of the pom of ‘GitTest’ project.
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-assembly-plugin</artifactId>
      <executions>
    	<execution>
    	  <id>create-my-bundle</id>
    	  <phase>package</phase>
    	  <goals>
    		<goal>single</goal>
    	  </goals>
    	  <configuration>
    		<descriptorRefs>
    		  <descriptorRef>jar-with-dependencies</descriptorRef>
    		</descriptorRefs>		        
    	  </configuration>
    	</execution>
      </executions>
    </plugin>
  2. This assembly plugin is bound to the package phase of the project. It has only a single goal named ‘single’ the rest of the goals are deprecated. The ‘descriptorRef’ element is the most important since that tells the plugin what to do. In this case since we have specified ‘jar-with-dependencies’ we are going to get two jars one with just the main project and the other with all it’s dependencies packaged together in a single jar. More info in http://maven.apache.org/plugins/maven-assembly-plugin/
  3. Now run the mvn package command either from Eclipse or the command line. You should see something like this in the console output.
          Building jar: C:\Users\sasurendran\Dropbox\Practicals\SmartGitMaven\personal\GitTest\target\gittest-0.0.1-SNAPSHOT.jar
          Building jar: C:\Users\sasurendran\Dropbox\Practicals\SmartGitMaven\personal\GitTest\target\gittest-0.0.1-SNAPSHOT-jar-with-dependencies.jar
  4. Go to the target directory in which the jar was built and open the gittest-0.0.1-SNAPSHOT-jar-with-dependencies.jar. You will see the ‘com’ package will have ‘gittest’ and ‘jarproject’ sub-packages. This is the combined jar will all the dependencies.
  5. Open the gittest-0.0.1-SNAPSHOT.jar and the ‘com’ package will only have ‘gittest’.
  6. There are several other supported format. You can use the descriptorRef ‘bin’ to create a binary in either tar.gz, tar.bz2 or zip format or use the descriptorRef ‘src’ to create source archives. More info at http://maven.apache.org/plugins/maven-assembly-plugin/descriptor-refs.html

Posted February 13, 2013 by salilsurendran in Technology

Tagged with