最近,Peter Ledbrook撰写了一篇名为《Spring:Grails的基础》的文章,透过这些文字,我们可以了解Spring和Grails的关系,及其在Grails中发挥的作用。
Grails本身也是一个Spring MVC应用,拥有自己的DispatcherServlet、ApplicationContext和相关的Bean,典型的Grails一般都有:
- grailsApplication – 代表当前应用及其资源的Bean
- pluginManager – 插件管理器,你可以通过它查询已加载插件的信息
- jspViewResolver – 自定义的GSP MVC视图解析器,在找不到相关GSP的情况下会去找JSP
- messageSource – 本地化的消息源
- localeResolver – 确定用户的locale
- annotationHandlerMapping – 允许使用@Controller注解
除了Web层,象其它如GORM、事务等,都离不开Spring的支持。正如Peter所言:
因此,Grails应用实际就是Spring应用。
在文章的第二部分,Peter着重解释了Grails和Spring之间的交互。如果你仔细阅读过Grails的参考文档,那么对于该部分的前两项内容(服务和自动装配,手动定义Bean)应该不会陌生。
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)
虽然简单,但文章已经给读者勾勒出了Grails和Spring的关系,以及它们之间的基本交互方式,请务必阅读原文,了解其中的详细内容。