Over a million developers have joined DZone.

Groovy Goodness: Extend ConfigSlurper with Custom Environments Sections

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

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 propertymail.host different values per environment:

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

    prod {
        mail.host = '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)
    configSlurper
}

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

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


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

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

Code written with Groovy 2.3.

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}