Gradle构建依赖性抛出ClassNotFoundException

时间:2014-04-07 11:31:26

标签: java maven gradle dependency-management build.gradle

我目前正在编写我的第一个Gradle构建脚本,以帮助构建一个从命令行使用的简单Java应用程序。

以下是完整的build.gradle代码

apply plugin: 'java'
apply plugin: 'eclipse'

defaultTasks 'clean', 'build'

repositories {
    mavenCentral()
}

jar {
baseName = 'napier-deploy'
version =  '1'
manifest {attributes 'Main-Class': 'com.Main'}
}

dependencies {
    compile 'org.apache.httpcomponents:fluent-hc:4.3.3'
    compile 'org.apache.httpcomponents:httpclient-cache:4.3.3'
    compile 'org.apache.httpcomponents:httpcore:4.1'
    compile 'org.apache.httpcomponents:httpmime:4.3.3'
    compile 'org.apache.httpcomponents:httpclient:4.3.3'

    testCompile 'junit:junit:4.11'
    testCompile 'org.mockito:mockito-all:1.9.5'
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.11'
}

运行gradle assemble --info命令显示从Maven下载的依赖项,但是当我尝试从命令行启动Jar时,我收到以下错误:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/HttpEntity
    at com.Main.main(Main.java:17)
Caused by: java.lang.ClassNotFoundException: org.apache.http.HttpEntity
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 1 more

HttpEntity包含在httpcomponents.httpcore artefact中,因此我不明白为什么JVM在查找类时遇到问题。

任何评论都表示赞赏。

2 个答案:

答案 0 :(得分:6)

经过一些研究后,我使用以下构建脚本成功构建了我的Jar。

apply plugin: 'java'
apply plugin: 'eclipse'

defaultTasks 'clean', 'build'

repositories {
    mavenCentral()
}

jar {
    from {
        configurations.compile.collect {
            it.isDirectory() ? it : zipTree(it)
        }
        configurations.runtime.collect {
            it.isDirectory() ? it : zipTree(it)
        }
    }
    manifest {
        attributes 'Implementation-Title': 'ndeploy',
            'Implementation-Version': '0.1.0',
            'Built-By': System.getProperty('user.name'),
            'Built-Date': new Date(),
            'Built-JDK': System.getProperty('java.version'),
            'Main-Class': 'com.Main'
    }
}

dependencies {
    compile 'org.apache.httpcomponents:fluent-hc:4.3.3'
    compile 'org.apache.httpcomponents:httpclient-cache:4.3.3'
    compile 'org.apache.httpcomponents:httpcore:4.1'
    compile 'org.apache.httpcomponents:httpmime:4.3.3'
    compile 'org.apache.httpcomponents:httpclient:4.3.3'
    testCompile 'junit:junit:4.11'
    testCompile 'org.mockito:mockito-all:1.9.5'
}

buildscript {
    dependencies {
        classpath fileTree(dir: '../../build/libs', include: '*.jar', excludes: ['*javadoc.jar', '*sources.jar'])
    }
}

赞赏的评论

答案 1 :(得分:1)

由于运行时配置还包含编译配置,因此您可以从上面的示例中排除收集编译配置的代码片段。