import org.codehaus.groovy.grails.commons.ApplicationHolder
//…
def book = ApplicationHolder.application.getClassForName("Book").findByTitle("Groovy in Action")
---------------------------------------------------------------------------------------
import org.codehaus.groovy.grails.commons.ApplicationHolder as AH
import org.springframework.web.context.WebApplicationContext as WAC
def ctx = AH.application.parentContext.servletContext.attributes.(WAC.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)
def svc = ctx.emailService
Grails同样也支持Spring的注解,但前提是要在grails-app/conf/Config.groovy里进行配置,指定要扫描的包:
1
grails.spring.bean.packages = [
"org.example"
]
此外,Peter还给出了在Grails中获得WebApplicationContext的代码示例:
1
import
org.springframework.web.context.support.WebApplicationContextUtils
2
import
org.codehaus.groovy.grails.web.context.ServletContextHolder
3
import
org.springframework.context.ApplicationContext
4
...
5
def
ctx = WebApplicationContextUtils
6
.getWebApplicationContext(ServletContextHolder.servletContext)