A Guide to Groovy DSL: Configuration

In part 1, we saw how to design a declarative API to be consumed as a Groovy DSL at a compiled environment. This part focuses on how to load them dynamically as “configuration”.

“Literally”, Configuration as code

You must be familiar with using YAML, JSON or (God forbid!) XML for configuration. One of the serious drawback of these languages are they are declarative and carry no logic. However, using Groovy, you can create configuration as Groovy code.

This has several advantages — You can use the full power of the Groovy programming language to define “reactive” configurations. Also, you are no longer limited by the declarative-ness of a declarative language and hence can use fancy things like loops, etc.

Replacing static configuration files

The simplest way of getting started with Groovy configuration is to start with replicating the behavior of the current starting configuration files.

The ConfigSlurper class can be used to parse Groovy scripts with configuration information. Using the ConfigSlurper we can parse Groovy scripts into a ConfigObject. The ConfigObject is a subclass of LinkedHashMap and contains the configuration information.

def slurper = new ConfigSlurper()def appConfig = appSlurper.parse(new File('application.groovy'));

appConfig will now have a key called pipeline.job.timeout with the value of 12000. In a Groovy context, this can be used as appConfig.pipeline.job.timeout

However, ConfigSlurper is a bit limiting approach. The code still feels declarative and doesn’t yet utilize some of Groovy’s features such as dynamic typing.

Part 3 will be addressing these — loading a full fledged Groovy configuration and running an application based on these features. Till then, stay tuned!

Computer Whisperer. Open-source contributor. Find me at https://amitosh.in/