News and Notes from the Makers of Nexus | Sonatype Blog

How to make an executable jar in Maven

Written by Brian Fox | August 13, 2009

It's been a while since I posted, so here's a quick and dirty code by example:

If you want to make a standalone jar (ie one with no dependencies) executable, here's how you do it:

<pluginManagement>
<plugins>
<plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
              <mainClass>com.yourcompany.YourClass</mainClass>
            </manifest>
         </archive>
       </configuration>
    </plugin>
  </plugins>
</pluginManagement>

If however you have dependencies, you will probably want to bundle them into a single jar, otherwise making it executable is not very helpful. You can use the assembly plugin to do it like this:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-assembly-plugin</artifactId>
    <executions>
      <execution>
         <goals>
           <goal>attached</goal>
         </goals>
<phase>package</phase>
         <configuration>
           <descriptorRefs>
             <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
          <archive>
            <manifest>
              <mainClass>com.yourcompany.YourClass</mainClass>
            </manifest>
          </archive>
        </configuration>
     </execution>
  </executions>
</plugin>

A few comments:

  1. I didn't specify plugin versions in the example. You should always specify a plugin version, but you should do it in the pluginManagement section instead. See this post for how and why.
  2. Notice the assembly plugin configuration has an execution, while the jar plugin does not. This is because the jar plugin will run automatically based on the packaging, which is assumed to be "jar" in this example. The assembly plugin needs an execution to "bind" it to the lifecycle and here we tell it which goal to run and which phase to run in.
  3. Notice also that the jar plugin is configured in pluginManagement. This is my personal best practice and I explain why here.

See more Maven How-Tos and Best Practices here.