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

时间:2015-08-21 17:33:03

标签: java jar gradle dependencies 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: '+'

}

感谢您的帮助:)

1 个答案:

答案 0 :(得分:4)

最简单的方法是从要包含的依赖项的单独配置开始。我知道您只询问了一个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发布时,provided配置中的所有依赖项将在POM中显示为provided。使用JAR发布的xml。 Maven依赖关系解析器不会降低provided依赖关系,并且jar的用户不会在类路径上以类的重复副本结束。见Maven Dependency Scopes

相关问题