Gradle - 用IDEA生成可執行的jar檔

這邊以加入AmazionSQS的dependency為例

在使用gradle打包完jar檔後執行,發現會出現NoClassDefFoundError的錯誤訊息。

Error Log

rammus@Rammus-MacBook-Pro.local:~/workspace/HelloWorld/build$ java -jar libs/HelloWorld-1.0.jar
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: com/amazonaws/services/sqs/AmazonSQS
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: com.amazonaws.services.sqs.AmazonSQS
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more

解開jar檔後發現根本沒有dependency的library,google了很久之後,才找到必須在打包的task裡面加入dependency的語法[2]。

build.gradle

jar {
manifest {
attributes 'Main-Class': 'com.hello.aws.Main'
}

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

attributes 'Main-Class': 'com.hello.aws.Main'決定jar檔的進入點(Entry Point)
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }將相依的class都加入jar檔


編輯完build.gradle後可以在projectt根目錄下執行

./gradlew jar

或是透過IDE的gradle plugin執行task:jar

  • refresh
    refresh-gradle-project

  • run task:jar
    build-jar

Run

java -jar xxxxxxx.jar

Snippet

group 'com.hello.aws'
version '1.0'

apply plugin: 'java'
apply plugin: "io.spring.dependency-management"

sourceCompatibility = 1.5

repositories {
mavenCentral()
}

buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "io.spring.gradle:dependency-management-plugin:0.5.4.RELEASE"
}
}


dependencyManagement {
imports {
mavenBom 'com.amazonaws:aws-java-sdk-bom:1.10.47'
}
}

dependencies {
compile 'com.amazonaws:aws-java-sdk-sqs'
testCompile group: 'junit', name: 'junit', version: '4.11'
}

jar {
manifest {
attributes 'Main-Class': 'com.hello.aws.Main'
}

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

Reference