使用 org.springframework.web.context.ContextLoaderListener 監聽器 初始化 Spring

在web.xml種這樣配置

    <listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>   
    </listener>

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>    

以下是詳解

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。

這篇博文也算是對自己有很多幫助,希望對你有些幫助

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