Tuesday, August 21, 2018

How to build a jar from a multi-module project when using Gradle?

Leave a Comment

I'm working on a multi-module library project which I build with Gradle. I have a dependency to another module of this project in my dependencies section:

dependencies {     compile project(':my-other-module') } 

My problem is that I want to build a .jar file which only contains the local modules in the final file, not its transitive dependencies. I tried this:

jar {     from project(':my-other-module').configurations.compile.collect { zipTree it } } 

but this added all the transitive dependencies as well. I want to create a .jar which only contains my own files, so the users of this library can have their own versions of transitive dependencies. How can I do so?

1 Answers

Answers 1

Gradle has a compile-only dependency concept, similar to Maven's provided scope:

Compile-only dependencies are distinctly different than regular compile dependencies. They are not included on the runtime classpath and they are non-transitive, meaning they are not included in dependent projects.

The dependencies you don't want can be declared in the compileOnly configuration, rather than compile, eg:

dependencies { compileOnly 'javax.servlet:servlet-api:2.5' }

compileOnly is not even visible to unit tests, by default. We change this in a common gradle snippet which we include in each build:

// compileOnly isn't visible to tests by default, add it plugins.withType(JavaPlugin).whenPluginAdded {     sourceSets {         test.compileClasspath += configurations.compileOnly         test.runtimeClasspath += configurations.compileOnly     } } 

For the second part, for which I believe you want to create a single "fat" jar, I would suggest creating your jar using the very good Shadow Plugin, rather than manually extending the jar task. By default, the shadow plugin will not include anything in the compileOnly configuration in the resulting jar.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment