Using Gradle to build a jar with dependencies

Ben McCann picture Ben McCann · Feb 2, 2011 · Viewed 151.1k times · Source

I have a multiproject build and I put a task to build a fat jar in one of the subprojects. I created the task similar to the one described in the cookbook.

jar {
  from configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  manifest { attributes 'Main-Class': 'com.benmccann.gradle.test.WebServer' }
}

Running it results in the following error:

Cause: You can't change a configuration which is not in unresolved state!

I'm not sure what this error means. I also reported this on the Gradle JIRA in case it is a bug.

Answer

Ben McCann picture Ben McCann · Feb 4, 2011

Update: In newer Gradle versions (4+) the compile qualifier is deprecated in favour of the new api and implementation configurations. If you use these, the following should work for you:

// Include dependent libraries in archive.
mainClassName = "com.company.application.Main"

jar {
  manifest { 
    attributes "Main-Class": "$mainClassName"
  }  

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

For older gradle versions, or if you still use the "compile" qualifier for your dependencies, this should work:

// Include dependent libraries in archive.
mainClassName = "com.company.application.Main"

jar {
  manifest { 
    attributes "Main-Class": "$mainClassName"
  }  

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

Note that mainClassName must appear BEFORE jar {.