【问题标题】:How do I include a single dependency in my JAR with Gradle?如何使用 Gradle 在我的 JAR 中包含单个依赖项?
【发布时间】:2015-11-15 17:54:08
【问题描述】:

我从 Gradle 开始,我想知道如何将单个依赖项(在我的情况下为 TeamSpeak API)包含到我的 JAR 中,以便它可以在运行时可用。

这是我的 build.gradle 的一部分:

apply plugin: 'java'

compileJava {
    sourceCompatibility = '1.8'
    options.encoding = 'UTF-8'
}

jar {
    manifest {
        attributes 'Class-Path': '.......'
    }

    from {
        * What should I put here ? *
    }
}

dependencies {
    compile group: 'org.hibernate', name: 'hibernate-core', version: '4.3.7.Final'
    compile group: 'org.spigotmc', name: 'spigot', version: '1.8-R0.1-RELEASE'
    // Many other dependencies, all available at runtime...

    // This one isn't. So I need to include it into my JAR :
    compile group: 'com.github.theholywaffle', name: 'teamspeak3-api', version: '+'

}

感谢您的帮助:)

【问题讨论】:

  • 依赖项不存储在 jar 文件中。它们在 jar 文件之外,并且 Class-Path 清单条目包含该 jar 的相对路径。

标签: java jar gradle dependencies build.gradle


【解决方案1】:

最简单的方法是从要包含的依赖项的单独配置开始。我知道您只询问了一个 jar,但如果您向新配置添加更多依赖项,此解决方案将起作用。 Maven 有一个众所周知的名字,叫做provided,所以我们将使用它。

   configurations {
      provided
      // Make compile extend from our provided configuration so that things added to bundled end up on the compile classpath
      compile.extendsFrom(provided)
   }

   dependencies {
      provided group: 'org.spigotmc', name: 'spigot', version: '1.8-R0.1-RELEASE'
   }

   jar {
       // Include all of the jars from the bundled configuration in our jar
       from configurations.provided.asFileTree.files.collect { zipTree(it) }
   }

使用provided 作为配置的名称也很重要,因为当jar 发布时,您在providedconfiguration 中的任何依赖项都将在发布的POM.xml 中显示为provided罐。 Maven 依赖解析器不会拉下provided 依赖,并且您的 jar 用户不会在类路径上得到类的重复副本。见Maven Dependency Scopes

【讨论】:

  • 假设我有两个依赖项列表:一个包含在 jar 中,另一个不包含 - 我该怎么做? maven-shade-plugin 编译被包括在内但不提供。但在您的示例中,情况似乎相反。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-14
  • 2015-12-27
相关资源
最近更新 更多