Performance Zone is brought to you in partnership with:

Hi all, my name is Hubert A. Klein Ikkink. Not a very common name, right? To make things easier I just picked the first letters of my firstname and surname and came up with haki. So there you have it, now I am also known as Mr. Haki or mrhaki for short. You can read more blog postings at I am a passionate Groovy and Java developer based in Tilburg, The Netherlands. My goal is to write clean, elegant, user-centered and high quality software. You can find me on Google+ and Twitter. Hubert is a DZone MVB and is not an employee of DZone and has posted 173 posts at DZone. You can read more from them at their website. View Full User Profile

Groovy Goodness: Extend ConfigSlurper with Custom Environments Sections

  • submit to reddit

Groovy contains the useful ConfigSlurper for reading in configuration files where settings can be different for different environments. We only have to include an environments block and define values for configuration properties per environment. Since Groovy 2.3 we can add our own conditional configuration blocks and therefore don't have to put everything in an environments block.

In the following sample we define our own configuration block servers and use two environments local and prod. We given the different values per environment:

// Configuration script.
def config = '''
// Custom block with setting
// conditional per environment.
servers {
    local { = 'greenmail'

    prod { = 'mail.server'

environments {
    local {
        appName = 'local'
    prod {
        appName = 'production'

// Helper closure to create a new
// ConfigSlurper for the given environment and
// register servers as section with configuration
// per environment.
def createConfig = { env ->
    def configSlurper = new ConfigSlurper(env)
    configSlurper.registerConditionalBlock('servers', env)

// Create configuration slurper and
// set environment to prod.
def configuration = createConfig('prod').parse(config)

assert == 'mail.server'
assert configuration.appName == 'production'

// Create configuration slurper and
// set environment to local.
configuration = createConfig('local').parse(config)

assert == 'greenmail'
assert configuration.appName == 'local'

Code written with Groovy 2.3.

Published at DZone with permission of Hubert Klein Ikkink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)