Maven- Creating a Jar together with its dependency Jars into a single executable Jar file

Maven- Creating a Jar together with its dependency Jars into a single executable Jar file

Suppose your boss comes and ask you to create a standalone JAVA application. Assuming you being a MAVEN lover, you created a JAVA application using MAVEN dependency management tool. Now suppose you have some MAVEN dependencies that are needed by your JAVA application. Since, it’s a standalone application you will be packaging the target files in a JAR file. So, how will you include the dependent JARs with your target executable JAR.

We have two ways to add the dependencies to the generated JAR file. We can either package everything as one JAR, having all dependencies extracted and re-packages with the generated JAR. Alternatively, we can have our dependencies copied to a folder relative to the JAR and modify the manifest accordingly. I personally prefer first approach, so will talk about that only. To resolve this issue we will use Maven Assembly Plugin that will create the JAR together with its dependency JARs into a single executable JAR file. Just add below plugin configuration in your pom.xml file.

<build>
   <pluginManagement>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
               <archive>
                  <manifest>
                     <addClasspath>true</addClasspath>
                     <mainClass>com.your.package.MainClass</mainClass>
                  </manifest>
               </archive>
               <descriptorRefs>
                  <descriptorRef>jar-with-dependencies</descriptorRef>
               </descriptorRefs>
            </configuration>
            <executions>
               <execution>
                  <id>make-my-jar-with-dependencies</id>
                  <phase>package</phase>
                  <goals>
                     <goal>single</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
      </plugins>
   </pluginManagement>
</build>

After doing this don’t forget to run MAVEN tool with this command mvn clean compile assembly:single

Leave a Reply

Your email address will not be published. Required fields are marked *