1. 程式人生 > >SpringMVC中web.xml的配置理解

SpringMVC中web.xml的配置理解

在web.xml種這樣配置

    <listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>   
    </listener>
  • 1
  • 2
  • 3
  • 4
  • 5

ContextLoaderListener的作用就是啟動Web容器時,自動裝配  ApplicationContext.xml的配置資訊。因為它實現了ServletContextListener這個介面,在web.xml配置這個監聽器,啟動容器時,就會預設執行它實現的方法。

applicationContext的預設的路徑是”/WEB-INF/applicationContext.xml。也可以在web.xml中配置該檔案的其他位置,配置如下:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>    
  • 1
  • 2
  • 3
  • 4
  • 5

以下是詳解

org.springframework.web.context.ContextLoaderListener類實現了javax.servlet.ServletContextListener介面。ServletContextListener介面能夠監聽ServletContext物件的生命週期,因為每個web應用僅有一個ServletContext物件,故實際上該介面監聽的是整個web應用。

實現該介面的類在web.xml中作為監聽器配置後,當web應用啟動後,會觸發ServletContextEvent事件,呼叫ContextLoaderListener的contextInitialized(ServletContextEvent sce)方法。

這裡寫圖片描述

ContextLoaderListener通過一個ContextLoader物件來初始化Spring容器。在contextInitialized方法中呼叫contextLoader.initWebApplicationContext(event.getServletContext())。

ContextLoader類的initWebApplicationContext方法即可返回一個WebApplicationContext物件context。並通過servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context)將WebApplicationContext物件放置在ServletContext物件中。initWebApplicationContext方法通過呼叫以下方法例項化並設定WebApplicationContext物件。

這裡寫圖片描述

因此可以通過WebApplicationContextUtils.getWebApplicationContext(ServletContext sc)獲取WebApplicationContext。內部實現是通過servletContext物件查詢該物件,屬性名為WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE。