在UrlMappings中使用grailsApplication注入

时间:2011-12-17 00:28:25

标签: grails grails-controller

出于某种原因,我在使用以下代码时会收到大量错误:

class UrlMappings {
    static grailsApplication
    static mappings = {

    grailsApplication.controllerClasses.each { controllerClass -> // FAILS!
        println(controllerClass.name)
    }

    "/$controller/$action?/$id?"{}

    "/"(view:"/index")
    "500"(view:'/error')
}

错误:http://pastebin.com/tiEsENie


以下代码的工作正常并打印所有控制器名称:

class UrlMappings {
    static grailsApplication
static mappings = {

    "/$controller/$action?/$id?"{
        grailsApplication.controllerClasses.each { controllerClass -> // WORKS!
            println(controllerClass.name)
        }
    }

    "/"(view:"/index")
    "500"(view:'/error')
}
}

是否可以从grailsApplication内部访问静态static mappings

(我需要能够获取控制器名称才能动态创建urlmappings)

1 个答案:

答案 0 :(得分:2)

虽然ApplicationHolder仍然有效,但是grails docs在弃用评论中说明了这一点


已弃用:使用依赖注入或实现GrailsApplicationAware


由于grailsUrlMappingsHolderBean实现GrailsApplicationAware,我发现下面的代码也适用于2.0

class UrlMappings {
    static mappings = {        
        getGrailsApplication().controllerClasses.each{ controllerClass -> 
            if(controllerClass.name./*your logic here*/){
                "/mod/action" {
                    controller = "${controllerClass.name}"
                }
            }
        }
    }
}