使用Grails 3应用程序在doWithSpring闭包中获取应用程序配置

时间:2015-04-13 19:52:48

标签: grails grails-3.0

Grails 3允许作者使用类似于Grails 2插件提供的启动挂钩。我正在考虑在doWithSpring闭包中定义bean,并且我想根据一些配置值将值传递给新bean。但是,我无法弄清楚如何获取grailsApplication实例或应用程序配置。你是如何用Grails 3做的?

2 个答案:

答案 0 :(得分:2)

您的插件应该扩展grails.plugins.Plugin,它定义了getConfig()方法。请参阅https://github.com/grails/grails-core/blob/9f78cdf17e140de37cfb5de6671131df3606f2fe/grails-core/src/main/groovy/grails/plugins/Plugin.groovy#L65

您应该只能引用config属性。

同样,您可以引用在https://github.com/grails/grails-core/blob/9f78cdf17e140de37cfb5de6671131df3606f2fe/grails-core/src/main/groovy/grails/plugins/Plugin.groovy#L47定义的继承的grailsApplication属性。

我希望有所帮助。

答案 1 :(得分:1)

在Grails 3下,我接受了Jeff Scott Brown的建议并使用了GrailsApplicationAware:

这是设置配置bean的方法:

所以在你的新插件描述符中,你需要将grails 2 style def doWithSpring更改为ClosureDoWithSpring,如下所示:

注意在Grails 2中我们注入了grailsApplication,在grails 3中我们所做的就是声明bean:

/*
    def doWithSpring = {
        sshConfig(SshConfig) {
          grailsApplication = ref('grailsApplication')
        }
    }
*/
   Closure doWithSpring() { {->
        sshConfig(SshConfig)
        } 
    }

现在来获取插件配置:

的src /主/常规/ Grails的/插件/ remotessh / SshConfigSshConfig.groovy

package grails.plugin.remotessh

import grails.core.GrailsApplication
import grails.core.support.GrailsApplicationAware

class SshConfig implements GrailsApplicationAware {

    GrailsApplication grailsApplication


    public ConfigObject getConfig() {
        return grailsApplication.config.remotessh ?: ''

    }

}

grails.plugin.remotessh.RemoteSsh.groovy:

String Result(SshConfig ac) throws InterruptedException {

        Object sshuser = ac.config.USER ?: ''
        Object sshpass = ac.config.PASS ?: ''
...

现在,您的配置对象将传递到您的src groovy类中。最终用户应用程序将传递sshConfig bean,如下所示:

class TestController {

    def sshConfig

    def index() {
        RemoteSSH rsh = new RemoteSSH()
      ....
        def g = rsh.Result(sshConfig)
    }

编辑添加,刚发现这个:)这是相关或重复的问题:

http://grails.1312388.n4.nabble.com/Getting-application-config-in-doWithSpring-closure-with-a-Grails-3-application-td4659165.html