繁体   English   中英

如何在Mixin中访问GrailsApplication?

[英]How to Access GrailsApplication in a Mixin?

我正在创建一个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
                }

您可以使用多种技术之一从应用程序中的任何位置访问grailsApplication 不推荐使用GrailsApplicationHolder ,但是Burt Beckwith 在此博客中提供了一些解决方案

可能最简单的方法是将其从现有域中拉出,如下所示:

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

他还有另一种方法在这里使用metaClass在BootStrap中设置变量


另外,您可以使用此博客文章中涉及更多但(我认为)更好的技术来创建用于访问应用程序的专用类。 如果要在多个地方使用它,那就很好了。 我在应用程序中创建了一个专用的AppCtx类,该类具有用于grailsApplicationconfig等的getters。用这种方式编写它要干净得多:

def foo = AppCtx.grailsApplication...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM