Tomy Tomy - 6 months ago 39
Java Question

Import only one dependency in Java Maven project

I need to make a jar out of my Java project, and I need it to also contain the class files of one of the dependencies, but not all of them. I've used

maven-assembly-plugin
which includes all the files and creates a huge jar, but I only need

<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.10.45</version>
</dependency>


I've also tried the maven shade plugin but with no result: I somehow end up including all the dependencies or excluding all of them

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<excludes>
<exclude>org.apache.spark:*</exclude>
<exclude>com.google.code.gson:*</exclude>
<exclude>edu.stanford.nlp:*</exclude>
<exclude>log4j:*</exclude>
<exclude>com.optimaize.languagedetector:*</exclude>
<exclude>info.debatty:*</exclude>
</excludes>
</artifactSet>
</configuration>
</execution>
</executions>
</plugin>

Answer

Use 'provided' for the scope tag of the dependencies that you don't want to include in the final jar file.

<dependency>
    <groupId>GROUP_ID</groupId>
    <artifactId>ARTIFACT_ID</artifactId>
    <version>VERSION</version>
    <scope>provided</scope>
</dependency>

And use maven-assembly-plugin to build the jar

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
        <archive>
            <manifest>
                <mainClass>MAIN_CLASS</mainClass>
            </manifest>
        </archive>
    </configuration>
</plugin>