9

我正在开发我的第一个 Grails 插件。它必须访问网络服务。插件显然需要网络服务 url。在不将其硬编码到 Groovy 类中的情况下配置它的最佳方法是什么?对于不同的环境使用不同的配置会很好。

4

2 回答 2

13

您可能希望保持简单(tm)。您可以直接在 Config.groovy 中定义 URL - 包括每个环境的设置 - 并根据需要使用 grailsApplication.config(在大多数情况下)或 ConfigurationHolder.config 对象从您的插件访问它(请参阅手册中的更多详细信息)。

作为额外的好处,该设置也可以在标准 Java 属性文件或 grails.config.locations 中指定的其他配置文件中定义。

例如在 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
  }
}

稍后,在您的插件提供的服务中

import org.codehaus.groovy.grails.commons.ConfigurationHolder
class MyPluginService {
  def url = ConfigurationHolder.config.myPlugin.url
  // ...
} 
于 2009-05-09T23:01:10.917 回答
7

如果它只是一个小的(读取:一个项目)配置选项,那么在属性文件中啜饮可能会更容易。如果有一些配置选项,并且其中一些应该是动态的,我建议执行 Acegi Security 插件所做的事情 - 可能将文件添加到 /grails-app/conf/plugin_name_config.groovy。

额外的好处是用户可以执行 groovy 代码来计算他们的配置选项(比使用属性文件要好得多),并且能够轻松地完成不同的环境。

查看http://groovy.codehaus.org/ConfigSlurper,这是 grails 内部用于 slurp 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
于 2009-05-09T14:28:50.717 回答