Working with JAR files in Maven

Posted in java, maven, work at 1:29 pm by Josh Peters

Apache Maven has become my build tool of choice at work. It seems that nearly every week I learn how to do something new with Maven (part of this is my inexperience, part is the plethora of awesome plug-ins).

I’ve been working on a project lately that is a pretty simple management application that uses JPA in the data layer. One of the goals of this project is to provide a nightly process for parsing input files. I could have tackled this in a variety of ways. My first hope was to create an executable JAR file, but I quickly found that I couldn’t get very far due to a limitation/feature of JARs: one cannot modify the classpath via the command line interface. My project uses some platform-specific files, so I could not easily include them in the final package. My second attempt ended up working well: create a JAR file within my WAR and execute a class inside that particular JAR.

This project has quite a lot of dependencies: Spring MVC, Hibernate, JPA, Javamail, SQL Server, etc. If I were to create a command-line call to the java executable it would quickly fill up many, many lines in an editor. Fortunately, it’s easy to include the classpath inside the JAR manifest during the Maven package:


<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-war-plugin</artifactId>
  <configuration>
    <archiveClasses>true</archiveClasses>
    <archive>
      <manifest>
        <addClasspath>true</addClasspath>
        <mainClass>…</mainClass>
      </manifest>
    </archive>
  </configuration>
</plugin>

The <addClassPath> bit tells Maven to include all of the other dependencies in the manifest file. This is a big deal, as it accomplishes two things: it takes care of me having to write a script to generate the classpath dynamically and it allows me to have a very reasonable length command line statement.

Thanks to letting Maven create a JAR file with its manifest managing the classpath, my resulting java command looks like this: java -cp MyProject.jar:… MyProjectRunner (where MyProjectRunner is a class that I want to execute).

Track with co.mments

Leave a Reply

Spam Protection by WP-SpamFree