【问题标题】:Including specific external library to a jar file built by Gradle将特定的外部库包含到 Gradle 构建的 jar 文件中
【发布时间】:2018-06-18 23:12:16
【问题描述】:

我正在尝试将多模块项目构建过程从 Ant 转换为 Gradle。 我们有一个通用模块,所有其他模块都使用它。在通用模块中,我需要这些依赖项才能编译它(通过 gradle build)

dependencies {
    api 'com.google.guava:guava:18.0'
    api 'org.json:json:20131018'
    implementation 'org.apache.httpcomponents:httpclient:4.5.5'
    implementation 'org.jruby:jruby-complete:1.5.1'
    implementation 'org.python:jython:2.2.1'
    implementation 'com.google.code.gson:gson:2.6.2'
}

一些模块应该在结果 jar 文件中包含运行时所需的所有依赖项。因此,我也将模块依赖项的代码添加到 jar 文件中。如下:

dependencies {
    compile project(':core:common')
    compile project(':core:installer')
}

jar {
    from sourceSets.main.output
    from project(':core:common').sourceSets.main.output
    from project(':core:installer').sourceSets.main.output   
}

问题是我也想将外部库添加到 jar 文件中,以便我拥有完整的 jar 文件。可以通过在上面的 jar 中添加一行来添加外部库,如下所示:

jar {
    from sourceSets.main.output
    from project(':core:common').sourceSets.main.output
    from project(':core:installer').sourceSets.main.output

    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }

}

但是我将有一个大的 jar 文件,其中包含公共模块中的所有依赖项,而我的特定 jar 文件中不需要其中一些依赖项。我想要的是将特定的外部库添加到 jar 文件中,例如我只想将 'org.json:json:20131018' 和 'org.apache.httpcomponents:httpclient:4.5.5' 添加到库中并忽略其余的依赖项。我找不到解决方案。

【问题讨论】:

    标签: java gradle jar build dependencies


    【解决方案1】:

    我通过将以下代码添加到 jar 中解决了这个问题:

    jar {
        from sourceSets.main.output
        from project(':core:common').sourceSets.main.output
        from project(':core:installer').sourceSets.main.output
        def libraries =['httpclient-4.5.5.jar','json-20131018.jar']
        from configurations.runtimeClasspath.
                findAll { libraries.contains(it.name)}.
                collect { zipTree(it) }      
    }
    

    但我认为 Gradle 仍然应该提供更好的解决方案来将外部库包含或排除到 jar 文件中。

    我在上面一点点更新了解决方案,我认为这是一种更好的方法,因为我们不需要指定 jar 文件。我们可以这样定义配置:

    configurations {
        runtimeLibraries
    }
    dependencies {
        compile project(':core:common')
        compile project(':core:installer')
        runtimeLibraries 'org.apache.httpcomponents:httpclient:4.5.5', 'org.json:json:20131018'
    }
    

    然后我们可以更新Jar任务如下:

    jar {
        from sourceSets.main.output
        from project(':core:common').sourceSets.main.output
        from project(':core:installer').sourceSets.main.output
        from configurations.runtimeLibraries.collect { zipTree(it) }
    }
    

    这两种方法的结果的一个区别是,通过定义配置,gradle 将识别所需的依赖关系并将它们添加到 jar 中。例如,如果您在创建的 jar 文件中使用 commons-net:commons-net:1.4.1 作为 runtimeLibraries 的一部分,您可以找到 commons-net 使用的 org.apache.oro 包

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2011-04-15
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      相关资源
      最近更新 更多