如何使用Gradle在我的JAR中包含单个依赖项?

Tlo*_*uus 6 java dependencies jar gradle build.gradle

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

这是我的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: '+'

}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助 :)

CaT*_*t.X 5

最简单的方法是从要包含的依赖项的单独配置开始.我知道您只询问了一个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) }
   }
Run Code Online (Sandbox Code Playgroud)

使用provided配置名称也很重要,因为当jar发布时,provided配置中的任何依赖项都将显示provided在使用JAR发布的POM.xml中.Maven依赖关系解析器不会拉下provided依赖关系,jar的用户也不会在类路径上找到类的重复副本.请参阅Maven依赖范围

  • 假设我有两个依赖项列表:一个包含在 jar 中,另一个不包含 - 我该怎么做?使用 `maven-shade-plugin` 编译被包含在内,但没有提供。但在你的例子中,情况似乎正好相反。 (3认同)