Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an executable fat jar with Gradle with implementation dependencies

I've got a simple project in Gradle 4.6 and would like to make an executable JAR of it. I've tried shadow, gradle-fatjar-plugin, gradle-one-jar, spring-boot-gradle-plugin plugins but neither of them adds my dependencies declared as implementation (I don't have any compile ones). It works with compile e.g. for gradle-one-jar plugin but I would like to have implementation dependencies.

like image 943
Dmitry Senkovich Avatar asked Mar 14 '18 12:03

Dmitry Senkovich


Video Answer


2 Answers

You can use the following code.

jar {     manifest {         attributes(                 'Main-Class': 'com.package.YourClass'         )     }     from {         configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }     }  } 

Be sure to replace com.package.YourClass with the fully qualified class name containing static void main( String args[] ).

This will pack the runtime dependencies. Check the docs if you need more info.

like image 134
miskender Avatar answered Sep 22 '22 23:09

miskender


Based on the accepted answer, I needed to add one more line of code:

task fatJar(type: Jar) {   manifest {     attributes 'Main-Class': 'com.yourpackage.Main'   }   archiveClassifier = "all"   from {     configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }     configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }     }   with jar } 

Without this additional line, it omitted my source files and only added the dependencies:

configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } 

For newer gradle (7+), you may see this error:

Execution failed for task ':fatJar'. > Entry [some entry here] is a duplicate but no duplicate handling strategy has been set. Please  refer to https://docs.gradle.org/7.1/dsl/org.gradle.api.tasks.Copy.html#org.gradle.api.tasks.Copy:duplicatesStrategy  for details. 

If this happens add a duplicatesStrategy such as duplicatesStrategy "exclude" to the fatJar task.

And likewise, for Gradle 7+, you have to just remove the configuration.compile.collect line because it is no longer a valid configuration in this version of gradle.

like image 30
JohnP2 Avatar answered Sep 25 '22 23:09

JohnP2