Monday, August 31, 2009

Create one stand-alone executable jar

Out of a sudden we realized that you cannot bundle library files (external jars) inside a jar file and create a Main class with MANIFEST.MF pointing to all the jar files bundled. We want to deliver our Java application as one jar file so the business analyst can execute it as
java -jar filename.jar

We always assumed that creating META-INF/MANIFEST.MF with the following settings would work:-
Main-Class: com.mydomain.mypackage.Main
Class-Path: *

filename.jar
| /META-INF
| | MANIFEST.MF
| | Main-Class: com.mydomain.mypackage.Main
| | Class-Path: spring.jar
| /com/mydomain/mypackage
| | Main.class
| spring.jar

It will work if the library files are outside the bundled jar file (containing the Main class) in the same directory.

The Java classloader does not know how to load classes from a Jar inside a Jar. The entries on the Class-Path must be references to files outside the Jar file, defeating the goal of delivering an application in a single Jar file.

The solution is to use : Fat Jar Eclipse Plugin. The tutorial is pretty neat and explains how to convert your Main method and bundle other library files along with it using Fat Jar plugin. Fat jar essentially explodes all the library files. It allows you to select a Main Class and creates a MANIFEST.MF file.

Now you can distribute one jar file to your customers :-)

No comments:

Post a Comment

Thank you for your feedback