Tuesday, November 1, 2011

How to Create a JAR with Dependencies in Gradle

Creating a single executable JAR/fat JAR can be pretty useful. We can do something like this.
java -jar foobar.jar
In Maven, we need to write a pretty verbose XML to do that as shown in my previous blog. In Gradle, this task can be easily achieved in just few lines as shown in the example below.
apply plugin: 'java'

sourceCompatibility = 1.6
targetCompatibility = 1.6

defaultTasks = ['clean', 'jar']

dependencies {
   compile 'org.slf4j:slf4j-api:1.6.2'
   compile 'ch.qos.logback:logback-core:0.9.30'
   compile 'ch.qos.logback:logback-classic:0.9.30'
   compile 'javax.servlet:servlet-api:2.5'
   compile 'org.eclipse.jetty.aggregate:jetty-all:7.5.4.v20111024' 
   
   testCompile 'junit:junit:4.+'
   testCompile 'org.mockito:mockito-core:1.8.5'
}

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

2 comments:

  1. bad idea if you have more than 65535 files in compile directory.

    ReplyDelete