Search code examples
gradleproperties-fileprofiles

How do I copy a file into my WAR based on profile?


I’m using Gradle 2.7 on Mac Yosemite. I have the following files:

src/main/environment/dev/context.xml
src/main/environment/qa/context.xml
src/main/environment/prod/context.xml

What I would like is if I run a build gradle -Pqa build, the appropriate context.xml file above is copied into my WAR (into the WEB-INF/classes directory is fine). How do I set this up with gradle?


Solution

  • There're many ways of solving the problem. You can configure sourceSets, or include or exclude particular resources when building war file. You can also have single context.xml and perform resource filtering with ReplaceTokens filter.

    I've chosen sourceSets:

    apply plugin: 'war'
    
    ext.env = project.hasProperty('env') ? project.env : 'dev'
    
    sourceSets {
       main {
          resources {
             srcDir "src/main/environment/$env"
          }
       }
    }
    

    The trick is to include/process only the env being passed. If no env is passed dev will be picked for further processing. Have a look a the demo.