Gradle构建的jar不具有运行依赖性

时间:2014-05-25 23:57:39

标签: gradle

这不是我第一次遇到这个问题。我试图使用Gradle来组装一个包含内部maven依赖项的.jar文件,以便我可以使用以下命令运行程序:

$ java -mx900m tregexWrapper-1.0.jar NP TaskSentence.txt

但是,考虑到我的jar文件(3kb)的大小,我觉得Gradle不太可能包含我想要的依赖。

结果如下:Exception in thread "main" java.lang.NoClassDefFoundError: edu/stanford/nlp/trees/tregex/TregexPattern

这是我的build.gradle文件,我甚至明确地将依赖项添加到runtime,但它没有帮助。

    apply plugin: 'java'
    apply plugin: 'idea'
    apply plugin: 'application'

    mainClassName = "Entry"

    sourceCompatibility = 1.5
    version = '1.0'

    jar {
        manifest {
           attributes 'Main-Class': 'Entry'
        }
    }

    repositories {
        mavenCentral()
    }

    dependencies {
        compile group: 'commons-cli', name: 'commons-cli', version: '1.2'
        compile group: 'edu.stanford.nlp', name: 'stanford-corenlp', version: '3.3.1'
        runtime(
             [group: 'commons-cli', name: 'commons-cli', version: '1.2'],
             [group: 'edu.stanford.nlp', name: 'stanford-corenlp', version: '3.3.1']
        )
    }

    run {
        if (project.hasProperty('args')) {
            args project.args.split('\\s+')
        }
    }

造成问题的原因是什么?

1 个答案:

答案 0 :(得分:0)

我使用sourceSets获得了良好的结果,如下所示:

jar {
  from files(sourceSets.main.output.classesDir)
  from files(sourceSets.main.output.resourcesDir)
  from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) {
      exclude "META-INF/*.SF"
      exclude "META-INF/*.DSA"
      exclude "META-INF/*.RSA"
  }
}

完整示例:

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'application'

version = '1.0'

repositories {
  mavenCentral()
}

dependencies {
  compile group: 'commons-cli', name: 'commons-cli', version: '1.2'
  compile group: 'edu.stanford.nlp', name: 'stanford-corenlp', version: '3.3.1'
  runtime(
    [group: 'commons-cli', name: 'commons-cli', version: '1.2'],
    [group: 'edu.stanford.nlp', name: 'stanford-corenlp', version: '3.3.1']
  )
}

sourceCompatibility = 1.7

mainClassName = "hello.Main"

//task superjar(type: Jar) {
jar {
  from files(sourceSets.main.output.classesDir)
  from files(sourceSets.main.output.resourcesDir)
  from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) {
      exclude "META-INF/*.SF"
      exclude "META-INF/*.DSA"
      exclude "META-INF/*.RSA"
  }
}

jar.doFirst {
  manifest {
    attributes 'Implementation-Title': 'Falkonry Gram',
                'Implementation-Version': version,
                'Built-By': System.getProperty('user.name'),
                'Built-Date': new Date(),
                'Built-JDK': System.getProperty('java.version'),
                'Main-Class': mainClassName
    }
}