Search code examples
gradlegradle-shadow-plugin

Configure Gradle Shadow plugin to create library jar with only one relocated dependency


My use case:

Use the Gradle Shadow plugin to build a Java library with a relocated Google Guice dependency (could be every other dep) to avoid dependency problems in the downstream project but leaves the other dependencies how they are. This means the downstream project still fetching these dependencies via a Maven repository because they are defined in the libraries pom.

I thought this is one of the main reasons to use this plugin, relocation of dependencies but still provide you project as a normal library like before. For me it was not really intuitiv to configure my use case. I would like to only enable relocation without creating an fatjar.

My example project works as expected, but I do not like that I need to define the dependencies twice as shadow and implementation.

shadow => The dependencies are added as runtime deps to the published pom (see code)

implementation => The dependencies used to compile the project itself e.g. in you IDE.

Do you know a better way?

Update:

The config in my example project is working for the Guice dependency because it is relocated as expected, but the transitive dependencies are missing. Of course this leads to a ClassNotFoundExecption (in my real project) because Guice does not found the classes of their own dependencies.


Solution

  • There is no other solution if you want to create a library jar with only one specific dependency to be relocate and the other ones of your project still in the published pom because of how the Shadow plugin works.

    So I updated my example project and found 2 possible solutions to also fix the problem with the missing transitive dependencies (siehe update block in my question).

    Option1: Adding all transitive dependencies (and the dependencies of the dependencies) to the shadowJar block: https://github.com/dacrome/gradle-shadow-plugin-example/tree/successful-config-option-1

    Option2: Adding just the first level dependencies of Guice to the dependencies block: https://github.com/dacrome/gradle-shadow-plugin-example/tree/successful-config-option-2

    I prefer Option1.