WebApplicationContext介绍

    WebApplicationContext是专门为web应用准备的,他容许从相对于web根目录的路劲中装载配置文件完成初始化工做,从WebApplicationContext中能够得到ServletContext的引用,整个Web应用上下文对象将做为属性放置在ServletContext中,以便web应用能够访问spring上下文,spring中提供WebApplicationContextUtils的getWebApplicationContext(ServletContext src)方法来得到WebApplicationContext对象java

 

WebApplicationContext扩展了ApplicationContext.在 WebApplicationContext中定义了一个常量 ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,在上下文启动时,web

WebApplicationContext以此为键放置在ServletContext属性列表中,spring

 

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

ConfigurableWebApplicationContext扩展了WebApplicationContext,它容许经过配置的方式实例化,同时设置两个重要方法spa

  setServletContext(ServletContext context) 为spring设置web应用上下文,以便二者整合3d

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

 

webApplicationContext初始化须要ServletContext,也就是说须要web容器前提下才能·完成启动工做  能够经过在web.xml中配置自启动Servlet或Web容器监听来实现web容器的启动xml

Spring分别提供启动WebApplicationContext的servlet和Web容器监听器对象

  org.springframework.web.context.ContextLoaderListener  blog

 org.springframework.web.context.ContexLoaderServlet     此方法目前以废弃get

!--从类路径下加载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>
相关文章
相关标签/搜索