Hamel Kothari
Hamel Kothari

Reputation: 737

Maven Include Dependency in Shaded Jar Only

I'd like to use maven shade to create a shaded jar, but I'd also like to include a special dependency only in the case of the shaded jar (not in the normal compile dependencies of my project). How can I go about this?

From my understanding the includes/excludes are only whitelists/blacklists so I can't explicitly force something to get included that wasn't included in the actual dependency list.

For more context, I have a JAR dependency which contains a resource that I only want included in one of my shade artifacts, but having that jar on the classpath otherwise would cause errors.

To be clear, I'm looking to generate both a shaded jar, with an additional dependency and a normal jar without it, in one mvn package call.

Upvotes: 6

Views: 2997

Answers (1)

dcsohl
dcsohl

Reputation: 7396

Try using a profile, and having your dependency and shade only in that profile. For example:

<profiles>
    <profile>
        <id>shadeProfile</id>
        <dependencies>
            <dependency>
                <groupId>com.example</groupId>
                <artifactId>some-artifact</artifactId>
                <version>1.23</version>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-shade-plugin</artifactId>
                    <version>2.3</version>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>shade</goal>
                            </goals>
                            <configuration>
                                <shadedClassifierName>shaded</shadedClassifierName>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

Now, when you run mvn -PshadeProfile package it will include the artifact as part of your shaded build, and use the classifier shaded for the new artifact. This way your build can produce your unshaded JAR without the problematic resource, and a shaded JAR with that resource, simply by turning on the profile.

Other projects which depend on this can either depend on the shaded or unshaded artifact, as appropriate, since you are using a classifier to generate both.

Upvotes: 5

Related Questions