如何使用 Gradle 将 jar 中的所有文件包含到 war 中

How to include all files from jar into war using Gradle

我正在尝试插件:

目前我正在尝试编写脚本:

dependencies {
    /* jar, his files I would like to include in war */
    compile project(':my_jar_1')
}

war {

    /* Step 1. Copy all from my_jar_1 into WEB-INF/classes */

    into('WEB-INF/classes') {
        from configurations.compile
                .filter { it.name.startsWith("my_jar_1") }
                .collect { zipTree(it).matching { exclude 'META-INF/**/*.*' }}
    }

    /* Step 2. Deleting jar from war WEB-INF/lib. I got stuck here. It println, but doesn't delete jar */

    doLast {
        zipTree('build/libs/war_1-0.0.0.war').files.each {
            if (it.path.endsWith('.jar')) {
                delete it
                println 'DELETED ' + it.path
            }
        }
    }
}

有人可以告诉我如何让它工作吗? 或者 smb 知道更优雅的解决方案?

我也试图声明我自己的配置

configurations { overlay }
dependencies { 
    overlay project(':my_jar_1') 
}
war {
        into('WEB-INF/classes') {
            from configurations.overlay
            ...

但是显示错误

FAILURE: Build failed with an exception.

  • What went wrong: Failed to capture snapshot of input files for task 'war' property 'rootSpec' during up-to-date check.

    Failed to create MD5 hash for file '/home/user/projects/OveralJarToWar/my_jar_1/build/libs/my_jar_1-1.0-SNAPSHOT.jar'.

WEB-INF/libWEB-INF/classes的内容由war任务的单个属性classpath配置。根据文档:

Any JAR or ZIP files in this classpath are included in the WEB-INF/lib directory. Any directories in this classpath are included in the WEB-INF/classes directory

因此,在您的情况下,类路径应修改如下

war {
    def myJar = project(':my_jar_1').jar.outputs
    def myClassesAndResources = project(':my_jar_1').sourceSets.main.output
    classpath = classpath - myJar + myClassesAndResources
}