Gradle make multiple war with different resources and classes

I have a Java web project, and I use Gradle to build project, the project structure as follow.

I want use Gradle to build 2 wars, main.war and api.war, and the wars structure as follow.

I have try many times to build these 2 wars, but when main.war is correct the api.war is wrong, when api.war is correct the main.war is wrong.

Could anyone give me some helps? Thanks.

project structure:

project-root
  |--src
    |--api
      |--resources
        |--api.xml
      |--webapp
        |--WEB-INF
          |--web.xml(api)
    |--main
      |--java
         |--xxx.xxx.api
         |--xxx.xxx.model
         |--some other packages
      |--resources
        |--main.xml
      |--webapp
        |--websrc
          |--js
          |--style
        |--WEB-INF
          |--web.xml(main)
        |--index.html

The wars structure I want:

main.war
  |--websrc
    |--js
    |--style
  |--WEB-INF
    |--classes
      |--all packages exclude api package
      |--main.xml
    |--web.xml(main)
  |--index.html
  api.war
  |--WEB-INF
    |--classes
      |--xxx.xxx.api
      |--xxx.xxx.model
      |--api.xml
    |--web.xml(api)

My gradle file :

task create_main_war(type: War, dependsOn: classes) {
    baseName = "main"
    rootSpec.exclude("**/api/**")
 }
  task create_api_war(type: War, dependsOn: classes) {
    baseName = "api"
    SourceSets {
        main.resources.srcDirs += "src/api/resources"
    }
    webAppDirName = "src/api/webapp
    rootSpec.exclude("**/main.xml")
    rootSpec.exclude("**/someOtherPackages/**")
 }

I think you want to separate the wars into two separate projects. It doesn’t make sense to build multiple WARs out of the same build.gradle unless most of the files in the WARs are going to be the same.

If you want ‘main.war’ to include the dependencies of ‘api.war’, you can reference the ‘providedCompile’ configuration from the ‘api.war’ project.

dependencies {
    compile project( path:':api-war', configuration:'providedCompile' )
}

Yes, I know separate the project into 2 sub projects and pre sub project have their build.gradle file may be better, but my 2 sub projects both use same packages, suck like: ‘xxx.model’ and ‘xxx.util’, so I don’t know how to separate is the right approach.

Alternatively, one could just declare a second ‘War’ task (or not use the ‘war’ plugin at all and declare two ‘War’ tasks).

@Peter Niederwieser, yes, but when one war take effect, the other is not correct. I think gralde can’t declare 2 wars in the same build.gradle file.

@Casey McGinty, Yes, I know separate the project into 2 sub projects and pre sub project have their build.gradle file may be better, but my 2 sub projects both use same packages, suck like: ‘xxx.model’ and ‘xxx.util’, so I don’t know how to separate is the right approach.