2009-05-09 106 views
9

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

回答

7

如果它只有一个小(阅读:一个项目)配置选项,它可能更容易在属性文件中啜泣。如果有一些配置选项,并且其中一些应该是动态的,我会建议做什么Acegi安全插件做 - 也许增加一个文件到/grails-app/conf/plugin_name_config.groovy。

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

检出http://groovy.codehaus.org/ConfigSlurper,这是grails在内部使用来配置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 
+0

奇怪的主意,有单独的配置文件只是一个物业服务,'Config.groovy'应使用该属性。 – tig 2013-02-11 01:40:54

+2

@tig AFAIK,当插件被打包时省略'Config.groovy',而不是测试插件而不是配置它,不是? – peterp 2013-07-01 15:36:37

13

您可能想要保持简单(tm)。您可以直接在Config.groovy中定义URL(包括每个环境设置),并根据需要使用grailsApplication.config(大多数情况下)或ConfigurationHolder.config对象(请参阅details in the manual)从插件中访问它。

作为额外的好处,该设置也可以在标准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 
    // ... 
}