【问题标题】:Configuration of Grails pluginGrails插件的配置
【发布时间】:2010-10-25 00:00:09
【问题描述】:

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

【问题讨论】:

    标签: grails plugins config


    【解决方案1】:

    您可能希望保持简单(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
      // ...
    } 
    

    【讨论】:

      【解决方案2】:

      如果它只是一个小的(读取:一项)配置选项,那么在属性文件中啜饮可能会更容易。如果有一些配置选项,并且其中一些应该是动态的,我建议执行 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
      

      【讨论】:

      • 奇怪的想法是为一个属性设置单独的配置文件,Config.groovy 应该用于该属性。
      • @tig AFAIK, Config.groovy 在插件打包时被省略,而不是用于测试插件而不是配置它,不是吗?
      猜你喜欢
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 2012-10-19
      • 2015-07-14
      相关资源
      最近更新 更多