views:

951

answers:

2

I'm developing my first Grails plugin. It has to access a webservice. The Plugin will obviously need the webservice url. What is the best way to configure this without hardcoding it into the Groovy classes? It would be nice with different config for different environments.

+4  A: 

If its only a small (read: one item) config option, it might just be easier to slurp in a properties file. If there are some number of configuration options, and some of them should be dynamic, i would suggest doing what the Acegi Security plugin does - add a file to /grails-app/conf/plugin_name_config.groovy perhaps.

added bonus is that the user can execute groovy code to compute their configuration options (much better over using properties files), as well as being able to do different environments with ease.

check out http://groovy.codehaus.org/ConfigSlurper , which is what grails internally use to slurp configs like config.groovy.

//e.g. in /grails-app/conf/MyWebServicePluginConfig.groovy
somePluginName {
   production {
      property1 = "some string"
   }
   test {
      property1 = "another"
   }
}

//in your myWebServicePlugin.groovy file, perhaps in the doWithSpring closure
GroovyClassLoader classLoader = new GroovyClassLoader(getClass().getClassLoader())
ConfigObject config
try {
   config = new ConfigSlurper().parse(classLoader.loadClass('MyWebServicePluginConfig'))
} catch (Exception e) {/*??handle or what? use default here?*/}
assert config.test.property1.equals("another") == true
Chii
+4  A: 

You might want to Keep It Simple(tm). You may define the URL directly in Config.groovy -including per-environment settings- and access it from your plugin as needed using grailsApplication.config (in most cases) or a ConfigurationHolder.config object (See further details in the manual).

As an added bonus that setting may also be defined in standard Java property files or on other configuration files specified in grails.config.locations.

e.g. in Config.groovy

// This will be the default value...
myPlugin.url=http://somewhe.re/test/endpoint
environments {
  production {
    // ...except when running in production mode
    myPlugin.url=http://somewhe.re/for-real/endpoint
  }
}

later, in a service provided by your plugin

import org.codehaus.groovy.grails.commons.ConfigurationHolder
class MyPluginService {
  def url = ConfigurationHolder.config.myPlugin.url
  // ...
}
codehead