我使用 gradle 构建了一个 fat jar,其中包含我的所有依赖项。现在,在使用 distZip 时,如何排除这些 jar 文件?

I used gradle to build a fat jar with all of my dependencies included in it. Now, when using distZip, how do I exclude these jar files?

所以这是我的 gradle 脚本:

apply plugin: 'java'
apply plugin: 'application'

mainClassName = "com.company.diagnostics.app.client.AppMain"

dependencies {

    compile ('commons-codec:commons-codec:1.8')
    compile (libraries.jsonSimple)
    compile ('org.apache.ant:ant:1.8.2')

    compile project(":app-common")

    testCompile 'org.powermock:powermock-mockito-release-full:1.6.2'

}

jar {

    archiveName = "app-client.jar"

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

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

    manifest {
        attributes 'Main-Class': 'com.company.diagnostics.app.client.AppMain"'
    }

    exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.MF'
}

构建时,它会生成如下所示的可分发 zip:

macbook-pro:distributions awt$ tree
.
├── app-client
│   ├── bin
│   │   ├── app-client
│   │   └── app-client.bat
│   └── lib
│       ├── ant-1.8.2.jar
│       ├── ant-launcher-1.8.2.jar
│       ├── commons-codec-1.8.jar
│       ├── app-client.jar
│       ├── app-common.jar
│       ├── guava-17.0.jar
│       ├── jetty-2.0.100.v20110502.jar
│       ├── json-simple-1.1.2.jar
│       ├── osgi-3.7.2.v20120110.jar
│       ├── services-3.3.0.v20110513.jar
│       └── servlet-1.1.200.v20110502.jar
└── app-client.zip

因为我已经使用我自己的自定义 jar 任务将依赖项捆绑到 jar 存档中,如何防止 distZip 第二次捆绑这些 jar 文件?

 - ant-1.8.2.jar
 - ant-launcher-1.8.2.jar
 - commons-codec-1.8.jar
 - guava-17.0.jar
 - jetty-2.0.100.v20110502.jar
 - json-simple-1.1.2.jar
 - osgi-3.7.2.v20120110.jar
 - services-3.3.0.v20110513.jar
 - servlet-1.1.200.v20110502.jar

将它们捆绑到 jar 任务中的原因是,这原本是一个独立的库。后来决定它也应该有一个命令行界面(因此,distZip 和自动创建 linux/mac/windows 的包装脚本)。它仍然需要作为一个独立的 fatjar 存在,所有依赖项都捆绑在其中。我只是不需要 /libs 中的这些多余内容。

如何让 distZip 排除它们?

您可以修改您的 distZip 任务,以排除您不希望出现在分发存档中的库,例如:

distZip {
    exclude 'ant-1.8.2.jar'
    exclude 'ant-launcher-1.8.2.jar'
    exclude 'commons-codec-1.8.jar'
    exclude 'guava-17.0.jar'
    exclude 'jetty-2.0.100.v20110502.jar'
    exclude 'json-simple-1.1.2.jar'
    exclude 'osgi-3.7.2.v20120110.jar'
    exclude 'services-3.3.0.v20110513.jar'
    exclude 'servlet-1.1.200.v20110502.jar'
}

或者可以通过 applicationDistribution,它为整个应用程序插件提供配置:

applicationDistribution.with {
    exclude 'ant-1.8.2.jar'
    exclude 'ant-launcher-1.8.2.jar'
    exclude 'commons-codec-1.8.jar'
    exclude 'guava-17.0.jar'
    exclude 'jetty-2.0.100.v20110502.jar'
    exclude 'json-simple-1.1.2.jar'
    exclude 'osgi-3.7.2.v20120110.jar'
    exclude 'services-3.3.0.v20110513.jar'
    exclude 'servlet-1.1.200.v20110502.jar'
}

您可以尝试将 exclude 更改为 include 以缩短文件列表,或者尝试将排除项绑定到依赖项列表。