WebApplicationContext介紹


    WebApplicationContext是專門為web應用准備的,他允許從相對於web根目錄的路勁中裝載配置文件完成初始化工作,從WebApplicationContext中可以獲得ServletContext的引用,整個Web應用上下文對象將作為屬性放置在ServletContext中,以便web應用可以訪問spring上下文,spring中提供WebApplicationContextUtils的getWebApplicationContext(ServletContext src)方法來獲得WebApplicationContext對象

 

WebApplicationContext擴展了ApplicationContext.在 WebApplicationContext中定義了一個常量 ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,在上下文啟動時,

WebApplicationContext以此為鍵放置在ServletContext屬性列表中,

 

public static WebApplicationContext getWebApplicationContext(ServletContext sc) {
        return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    }

ConfigurableWebApplicationContext擴展了WebApplicationContext,它允許通過配置的方式實例化,同時設置兩個重要方法

  setServletContext(ServletContext context) 為spring設置web應用上下文,以便兩者整合

setConfigLocations(String[]locations) 設置Spring配置的文件地址

 

webApplicationContext初始化需要ServletContext,也就是說需要web容器前提下才能·完成啟動工作  可以通過在web.xml中配置自啟動Servlet或Web容器監聽來實現web容器的啟動

Spring分別提供啟動WebApplicationContext的servlet和Web容器監聽器

  org.springframework.web.context.ContextLoaderListener  

 org.springframework.web.context.ContexLoaderServlet     此方法目前以廢棄

!--從類路徑下加載Spring配置文件,classpath特指類路徑下加載-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:smart-context.xml
        </param-value>
    </context-param>
    <!--負責啟動spring容器的監聽器  還可以聲明自啟動的Servlet   ContextLoaderServlet-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

 

如果使用@Configuration的java類提供配置信息的配置  web.xml配置修改如下

 <!--通過指定context參數,讓Spring使用AnnotationConfigWebApplicationContext啟動容器而非XmlWebApplicationContext   默認沒配置時是使用XmlWebApplicationContext-->
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
<!--指定標注了@Configuration的類,多個可以用逗號分隔-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.example.Car,com.example.Boss</param-value>
    </context-param>
    <!--監聽器將根據上面的配置使用AnnotationConfigWebApplicationContext
    根據contextConfigLocation
    指定的配置類啟動Spring容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM