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>

 

posted @ 2017-10-28 11:10  张秀杰  阅读(18620)  评论(0编辑  收藏  举报