Spring ContextLoaderListener 與 SpringMVC DispatcherServlet所加載的applicationContext的區別

本篇博客轉載自 http://user.qzone.qq.com/413670706/blog/1471574740

Spring通過在web.xml 中配置Listenter : org.springframework.web.context.ContextLoaderListener 來加載spring context配置文件,SpringMVC也可以通過在web.xml 中配置Servlet : org.springframework.web.servlet.DispatcherServlet來加載spring context配置文件,那麼這兩個有什麼區別呢。

ContextLoaderListener加載的spring context配置文件成功後,spring 將 applicationContext存放在ServletContext中key值爲"org.springframework.web.context.WebApplicationContext.ROOT"的attribute中。(servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context));可以通過WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)WebApplicationContextUtils.getWebApplicationContext(servletContext)方法來獲取對應的applicationContext。


 DispatcherServlet加載的spring context配置文件成功後,如果 publishContext屬性的值設置爲true的話(缺省爲true) 會將applicationContext存放在org.springframework.web.servlet.FrameworkServlet.CONTEXT. + (servletName)的attribute中。
       如:web.xml中配置如下



則對應的applicationContext的attribute key值爲org.springframework.web.servlet.FrameworkServlet.CONTEXT.DispatcherServlet 

 在每次request請求時,DispatcherServlet會將此applicationContext存放在request中attribute值爲 org.springframework.web.servlet.DispatcherServlet.CONTEXT中(request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE,getWebApplicationContext());)。可以通過RequestContextUtils.getWebApplicationContext(servletContext,attrname)WebApplicationContextUtils.getWebApplicationContext(servletContext,attrname)方法 來獲取對應的applicationContext。
 
從上面的分析可以看出,DispatcherServlet所加載的applicationContext可以認爲是mvc私有的context,由於保存在servletContext中的key值與通過ContextLoaderListener加載進來的applicationContext使用的key值不相同,因此如果只使用DispatcherServlet加載context的話,如果程序中有地方使用WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext) 來試圖獲取applicationContext時,就會拋出"No WebApplicationContext found: no ContextLoaderListener registered?"的exception。




解決此問題的方法:在web.xml 中配置Listenter : org.springframework.web.context.ContextLoaderListener 來加載spring context配置文件


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章