【问题标题】:Grails: How can I access application configuration from a command-line script?Grails:如何从命令行脚本访问应用程序配置?
【发布时间】:2011-08-14 06:57:10
【问题描述】:

我需要在我的 grails 应用程序中自定义命令行任务,因此我使用 grails create-script my-script 创建了一个脚本。

从该脚本中,我想访问一些应用程序的配置属性。通常,您可以通过grailsApplication.config 执行此操作。但是,似乎grailsApplication 在命令行脚本的上下文中不可用。以下脚本....

includeTargets << grailsScript("Init")

target(main: "The description of the script goes here!") {
    println  grailsApplication.config.mysetting
}

setDefaultTarget(main)

...产量(以grails my-script 运行时):

groovy.lang.MissingPropertyException: No such property:
                                      grailsApplication for class: MyScript

我也试过ConfigurationHolder.config,它只返回null。

那么如何从命令行启动的脚本访问应用程序配置?

【问题讨论】:

    标签: grails command-line configuration groovy


    【解决方案1】:

    诀窍是引入 boostrap 目标 并依赖它们,如下所示。请注意,应用程序上下文对象在这个阶段称为 grailsApp,而不是 grailsApplication

    includeTargets << grailsScript('_GrailsBootstrap')
    
    target(main: "The description of the script goes here!") {
        depends checkVersion, configureProxy, bootstrap
        println  grailsApp.config.mysetting
    }
    
    setDefaultTarget(main)
    

    您还可以使用run-script 命令。这对我不起作用,因为它试图初始化 Hibernate 会话。我的应用程序使用 mongodb 作为主数据存储,requires that you uninstall the Hibernate plugin - 所以运行脚本失败。

    【讨论】:

      【解决方案2】:

      1) 请参阅脚本顶部的 _GrailsPackage

      includeTargets << grailsScript('_GrailsPackage')
      

      2) 依赖于 _GrailsPackage

      中描述的 compile 和 createConfig 目标
      target(main: "Your main") {
          depends(compile,createConfig)
          println "My value: ${config.my.config.value}"
      }
      

      【讨论】:

        【解决方案3】:

        我还不能写评论,所以我发布一个答案。

        我认为使用 snowindy 建议的 _GrailsPackage 脚本的解决方案是首选。原因是使用bootstrap实际上是启动应用程序,这意味着连接到数据库,执行BootStrap.groovy等。只需使用_GrailsPackackecompile createConfig 依赖项只需要编译运行。

        取决于你的脚本做什么,这可能是你想要的。就我而言,我生成了一些可以通过 Config.groovy 中的设置自定义的 SQL 脚本,因此启动应用程序只会减慢速度。

        干杯, 本

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多