Injecting Spring Beans with data from Config

15 / Apr / 2010 by Vivek Krishna 2 comments

In one of the projects, we had to externalize the Config file to be in a properties file. All configurations related to the application were to be stored in that file. We had a few spring beans, like the JMS connection factory, which needs the brokerURL which should ideally be an external configuration as it is will be environment specific. An excellent approach to this issue could be seen in the mail plugin, wherein the bean is injected from config values.

An example resource.groovy similar to that would be

import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH
beans={
   sampleBean(com.intelligrape.Sample){        //Sample is a bean with a property value
        value = CH.config.app.sample.value?:'defaultValue'
                     //app.sample.value is a property in the config.groovy file
                     //If no config property is specified, set to 'defaultValue'
  }
}

Hope this helps

–Vivek

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Tim

    Nice, but you should be able to use Springs property override configuration. Set the default value in your resource.groovy as you have above. But when you want to override the property you can do this in you Config.groovy file.

    beans {
    sampleBean {
    value = “Whatever….”
    }
    }
    or beans.sampleBean.value = “Whatever….”

    This way you can also set that value to be environment specific.

    See Property Override Configuration for more information.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *