代码之家  ›  专栏  ›  技术社区  ›  Govan

将特定的外部库包含到Gradle构建的jar文件中

  •  1
  • Govan  · 技术社区  · 7 年前

    我正在尝试将多模块项目构建过程从Ant转换为Gradle。

    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'到库并忽略其余依赖项。我找不到解决办法。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Govan    7 年前

    我通过在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中。例如,如果您正在使用commons-net:commons-net:1.4.1作为创建的jar文件中runtimeLibraries的一部分,您可以找到由commons net使用的org.apache.oro包