Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
def config = new ConfigSlurper().parse(..)

new File("..").withWriter { writer ->
     config.writeTo(writer)
}

Special "environments" Configuration

The ConfigSlurper class has a special constructor other than the default constructor that takes an "environment" parameter. This special constructor works in concert with a property setting called environments. This allows a default setting to exist in the property file that can be superceded by a setting in the appropriate environments closure. This allows multiple related configurations to be stored in the same file.

Given this groovy property file:

Code Block

Sample.groovy
 

sample {
     foo = "default_foo"
     bar = "default_bar"
}

environments {
     development {
          sample {
               foo = "dev_foo"
          }
     }
     test {
          sample {
               bar = "test_bar"
          }
     }
}

Here is the demo code that exercises this configuration:

Code Block

def config = new ConfigSlurper("development").parse(new File('Sample.groovy').toURL())

assert config.sample.foo == "dev_foo"
assert config.sample.bar == "default_bar"

config = new ConfigSlurper("test").parse(new File('Sample.groovy').toURL())

assert config.sample.foo == "default_foo"
assert config.sample.bar == "test_bar"

Note: the environments closure is not directly parsable. Without using the special environment constructor the closure is ignored.

Further information

Using Groovy ConfigSlurper to Configure Spring Beans