简体   繁体   中英

Create Executable Jar that includes all the dependencies as packaged jars

I'm trying to understand how to include all of the dependencies in an executable jar file as packaged jars (ie include jars within a jar) but I'm failing miserably.

Could someone point me in the right direction please?

Note that I wan't the resultant fat jar to have jars packaged within it not the un-packaged equivalent that you get using the maven-assembly-plugin

What you want to create is called a fat jar . You can generate it by doing next steps.

Add Build section in your POM file as follows:

<build>
    <finalName>example</finalName>
    <plugins>

        <!-- Set a compiler level -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>${jdk.version}</source>
                <target>${jdk.version}</target>
            </configuration>
        </plugin>

        <!-- Maven Assembly Plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.4.1</version>
            <configuration>
                <!-- get all project dependencies -->
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <!-- MainClass in mainfest make a executable jar -->
                <archive>
                  <manifest>
                    <mainClass>com.example.Main</mainClass>
                  </manifest>
                </archive>

            </configuration>
            <executions>
              <execution>
                <id>make-assembly</id>
                <!-- bind to the packaging phase -->
                <phase>package</phase> 
                <goals>
                    <goal>single</goal>
                </goals>
              </execution>
            </executions>
        </plugin>

    </plugins>
</build>

Above “Maven Assembly Plugin” is bind to the Maven’s packaging phase , to produces the final Jar, just package it using:

mvn package

Two jar files will be created in the target folder.

  • example.jar – Only your project classes

  • example-jar-with-dependencies.jar – Project and dependency classes in a single jar.

You can now check the contents of your fat jar with:

jar tf target/example-jar-with-dependencies.jar 

Include dependencies in the pom.xml. Build the project using mvn clean install and the result will have these dependencies. You can then run the jar using

java -cp <jar Filename> <main class name>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM