One really useful task that one of my junior developers recently asked my help with was to create an executable jar from a maven project. He had mostly figured it out on his own but I still think this is a useful topic to cover. To achieve this we will be using the Maven Assembly plug-in running in Maven 3.

As a starting point of this implementation I will be using the sample code from an earlier article [Setting up a webservice using Guice & Sitebricks](/Programming/Java/2011/06/25/Setting-up-a-webservice-using-Guice-Sitebricks/) which can be downloaded from [github](https://github.com/techtraits/guice-server-example). First lets go and create our main class, Please add a Java class file at helloworld/src/main/java/com/flybynight/helloworld and add the following code to let us know or jar was packed properly.

package com.flybynight.helloworld;

public class Driver {
	public static void main(String[] args) {
		System.out.println("Hello");
	}
}

 

Next create a manifest file for your executable jar at src/main/resources/META-INF/MANIFEST.MF and add set the main class parameter to the Driver class we just wrote by adding the following text Main-Class: com.flybynight.helloworld.Driver.

Now create a assembly description file for you project, create a file at src/assemble/descriptor.xml and add the text below. We are defining an assembly execution called exe which will create an executable jar in the target directory. A detailed description of all the parameters in the descriptor file can be found here.

<assembly>
  <id>exe</id>
  <formats>
    <format>jar</format>
  </formats>
  <includeBaseDirectory>false</includeBaseDirectory>
  <dependencySets>
    <dependencySet>
      <outputDirectory></outputDirectory>
      <outputFileNameMapping></outputFileNameMapping>
      <unpack>true</unpack>
      <scope>runtime</scope>
      <includes>
      </includes>
    </dependencySet>
  </dependencySets>
  <fileSets>
    <fileSet>
      <directory>target/classes</directory>
      <outputDirectory></outputDirectory>
    </fileSet>
  </fileSets>
</assembly>

 

We are almost done now the last step is to add the maven assembly plug-in definition to our pom.xml file. Find the plugins tag in the xml and add the following lines here. Notice how we are referencing the manifest and descriptor file here.

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.2.2</version>
    <configuration>
        <descriptors>
            <descriptor>src/assemble/descriptor.xml</descriptor>
        </descriptors>
        <archive>
            <manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
        </archive>
    </configuration>
</plugin>

 

Now to test your code run the mvn assembly:assembly target to generate the execute the assembly plugin. You should now see the target/helloworld-exe.jar file. To test the jar run java -jar target/helloworld-exe.jar. You should see "hello" printed to console.