5

Grails 3 允许作者使用类似于为 Grails 2 插件提供的启动钩子。我正在考虑在doWithSpring闭包中定义 bean,并且我想根据一些配置值将值传递给一个新的 bean。但是,我不知道如何获取 grailsApplication 实例或应用程序配置。您如何使用 Grails 3 做到这一点?

4

2 回答 2

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#L47grailsApplication中定义的继承属性。

我希望这会有所帮助。

于 2015-04-17T20:27:29.007 回答
1

在 Grails 3 下,我采纳了 Jeff Scott Brown 的建议并改用 GrailsApplicationAware:

这是您设置配置 bean 的方式:

因此,在您的新插件描述符中,您需要将 grails 2 样式 def doWithSpring 更改为 ClosureDoWithSpring,如下所示:

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

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

现在获取您的插件配置:

src/main/groovy/grails/plugin/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

于 2015-04-18T18:29:30.643 回答