簡體   English   中英

Gradle:將類添加到JAR文件的類路徑中

[英]Gradle: Adding Classes to the JAR File's Classpath

我希望標題本身具有描述性,但要清楚一點,我試圖在greeting-service.jar中包含其中一個jar (即error-handling-service.jar )。 構建后,我在新項目(即TestApplication)中包含了greeting-service.jar,但是在執行TestApplication時我得到了(順便說一句,TestApplication不是gradle項目)

Exception in thread "main" java.lang.NoClassDefFoundError: co/common/exception/BaseException
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)

co.common.exception.BaseException是錯誤處理服務模塊中的類

根據這里的問題 包括我

manifest {
            attributes(
                    "Manifest-Version": "1.0",
                    "Class-Path": configurations.compile.collect { it.getName() }.join(' ')
            )
        }

這是greeting-service的build.gradle,它依賴於錯誤處理服務

buildscript {
    repositories {
        mavenCentral()
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'maven'

repositories {
    mavenCentral()
    mavenLocal()
}

dependencies {
    compile('org.apache.commons:commons-lang3:3.0')
    compile('org.apache.commons:commons-collections4:4.0')
    compile('org.slf4j:slf4j-api:1.7.25')
    compile('co.common:error-handling-service:1.0.0-SNAPSHOT')
    testCompile("org.mockito:mockito-all:1.9.5")
    testCompile('junit:junit:4.12')
}

jar {
    baseName = 'greeting-service'
    version = '1.0.0-SNAPSHOT'
    manifest {
        attributes(
                "Manifest-Version": "1.0",
                "Class-Path": configurations.compile.collect { it.getName() }.join(' ')
        )
    }
}

group = 'co.common'
version = '1.0.0-SNAPSHOT'

sourceCompatibility = 1.8
targetCompatibility = 1.8


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

成功構建greeting-service之后,我在TestApplication中包含了greeting-service.jar,但仍然收到上述相同的異常。

Manifest-Version: 1.0
Class-Path: commons-lang3-3.0.jar commons-io-2.4.jar commons-collections
 4-4.0.jar slf4j-api-1.7.25.jar error-handling-service-1.0.0-SNAPSHOT.
 jar commons-logging-1.1.3.jar

為什么會發生這種情況,應該怎么做?

當Java虛擬機在運行時無法找到編譯時可用的特定類時,Java中會出現NoClassDefFoundError 例如,如果我們從類中調用方法或訪問類的任何靜態成員,而該類在運行時不可用,那么JVM將拋出NoClassDefFoundError。

因此,假設您的gradle構建成功通過-我可能會得出結論,您提供的錯誤error-handling-service-1.0.0-SNAPSHOT.jar不包含co/common/exception/BaseException類。

您應該仔細檢查此罐子的實際內容。

不知道這是否有幫助,但是,如果您的error-handling-service.jar已經打包並准備作為依賴項包含在greeting-service.jar中,那么您應該使其成為依賴項。

例如:

  1. 在您的項目中,創建一個名為“ lib”的文件夾
  2. 將您的error-handling-service.jar添加到“ lib”文件夾中
  3. 將以下內容添加到您的依賴項塊中:

    依賴項{compile fileTree(dir:'lib',include:['* .jar'])...}

基本上,運行構建時,您放入“ lib”文件夾中的每個* .jar都會添加到應用程序jar中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM