HOW CAN I CREATE AN EXECUTABLE JAR WITH DEPENDENCIES USING MAVEN?

Ankita Pandey

Total Post:183

Points:1285
Posted by  Ankita Pandey
Java 
 790  View(s)
Ratings:
Rate this:

I have written a little utility to run from the command line using Java. I want to package it in a single executable jar for distribution (.jar file).

How can I make Maven package all dependency jars into my jar?

  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: How can I create an executable jar with dependencies using Maven?

    <build>
      <plugins>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <configuration>
            <archive>
              <manifest>
                <mainClass>fully.qualified.MainClass</mainClass>
              </manifest>
            </archive>
            <descriptorRefs>
              <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
          </configuration>
        </plugin>
      </plugins>
    </build>
    and you run it with

    mvn clean compile assembly:single
    Compile goal should be added before assembly:single or otherwise the code on your own project is not included.

    See more details in comments.

    Commonly this goal is tied to a build phase to execute automatically. This ensures the JAR is built when executing mvn install or performing a deployment/release.

    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <mainClass>fully.qualified.MainClass</mainClass>
          </manifest>
        </archive>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
      <executions>
        <execution>
          <id>make-assembly</id> <!-- this is used for inheritance merges -->
          <phase>package</phase> <!-- bind to the packaging phase -->
          <goals>
            <goal>single</goal>
          </goals>
        </execution>
      </executions>
    </plugin>

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!