Using the Grails BeanBuilder to Set Arbitrary Properties From an External Config

| Comments

I’m working with an existing library (Jedis a Redis client library) that has a fairly complicated connection pool config file with a large variety of potential properties that could be worth setting depending on the environment that my Grails app is running in.

I wanted the ability to define the set of properties that I wanted to override in the config file without having to call them all out explicitly in the Spring resources.groovy file. If I missed one, or if the client library that I’m using added a new one that I don’t notice, I don’t want to have to release a new version of the code just to set it.

Grails allows you to load external config files simply by defining a reference to them in Config.groovy (this code is even commented out in the default Config.groovy file that gets generated automatically with a new grails app):

grails.config.locations = ["file:${userHome}/.grails/${appName}-config.groovy"]

After a little playing around with the BeanBuilder syntax, I was able to come up with a solution that lets me set whatever values I want in the Config file and have them set on the bean that I have Spring/Grails build.

If you have a config like this:

foo {
    foo = "bar"
    baz = 4

You can populate your resources.groovy with something like this to set whatever values are set in your config file:

beans = {
    def fooMap = application.config?.foo

    fooBean(Foo) {
        fooMap?.each { key, value ->
            delegate.setProperty(key, value)

This will make a bean that has it’s foo set to “bar” and it’s baz set to 4.

Later, if I find that I need to set the baz property on the fooBean in production, I just add that in my config file and everything works without any code changes.