Friday, July 06, 2007

Groovy 1.1 beta 2 out. Configuration made easy with ConfigSlurper

So we've put out the 1.1 beta 2 release of Groovy, which is a really significant milestone for the project. Guillaume has the lowdown of all the new features in his blog.

One of the things I worked on for this release was a new utility class called ConfigSlurper. It allows you to write configuration files as Groovy scripts in a Java properties file like format. What advantage does this give you?

1) You get to take advantage of native Java types and not do type conversion from properties
2) You can use "global variables" and write more DRY configurations
3) You can take advantage of Groovy's advanced syntax for lists and maps to make config easier

Here is an example of configuring log4j with a ConfigSlurper script:


log4j.appender.stdout = "org.apache.log4j.ConsoleAppender"
log4j.appender."stdout.layout"="org.apache.log4j.PatternLayout"
log4j.rootLogger="error,stdout"
log4j.logger.org.springframework="info,stdout"
log4j.additivity.org.springframework=false


Not that disimilar from standard Java properties files and you can convert to and from Java properties files, merge configurations and serialize them back to disk. To use this this script you can use the ConfigSlurper class to parse it:


def config = new ConfigSlurper().parse(new File('myconfig.groovy').toURL())

assert "info,stdout" == config.log4j.logger.org.springframework
assert false == config.log4j.additivity.org.springframework


We're using this as our primary means to deal with necessary configuration (not possible by convention in Grails. Checkout some more examples of its usage here.

No comments: