如何在Mixin中访问GrailsApplication?

时间:2012-04-27 18:45:30

标签: grails controller mixins

我正在创建一个mixin来添加到我的控制器中,它具有一些基本的实用功能。我想在mixin中执行的一个功能是使用g.message taglib将错误解析为其字符串。不幸的是,我似乎无法访问静态mixin方法中的GrailsApplication

我如何从mixin访问Grails标签库,或者有更好的方法来实现我正在做的事情 - 在所有控制器之间共享公共代码?

这是我正在运行的代码。我认为问题是如何在静态方法中访问Grails标签库:

            static def preparePostResponse(domainInstance) {

                    def grailsApplication = new User().domainClass.grailsApplication


                    def postResponse = new AjaxPostResponse(domainObject: domainInstance)

                    if (domainInstance.hasErrors()) {
                        g.eachError(bean: domainInstance) {
                            postResponse.errors."${it.field}" = g.message(error: it)
                        }
                        postResponse.success = false
                        postResponse.message = "There was an error"
                    }
                    else {
                        postResponse.success = true
                        postResponse.message = "Success"
                    }
                    return postResponse
                }

1 个答案:

答案 0 :(得分:0)

您可以使用多种技术之一从应用程序的任何位置访问grailsApplicationGrailsApplicationHolder已被弃用,但Burt Beckwith有couple of solutions in this blog posting

最简单的一种方法就是将其从现有域中删除,如下所示:

class MyMixin {
    static myMethod() {
        def grailsApplication = new MyDomainClass().domainClass.grailsApplication
        // use it like normal here
    }
}

他有另一种设置variables in BootStrap using metaClass here的方法。


或者,您可以在this blog post中使用更多参与但更好的(我认为)更好的技术来创建用于访问应用程序的专用类。如果你打算在几个地方使用它,这很好。我在我的应用程序中创建了一个专用AppCtx类,其中包含grailsApplicationconfig等的getter。以这种方式编写它会更清晰:

def foo = AppCtx.grailsApplication...
相关问题