WebApplicationContext介绍

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

 

WebApplicationContext介绍_第1张图片

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);
    }

WebApplicationContext介绍_第2张图片

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>contextConfigLocationparam-name>
        <param-value>
            classpath:smart-context.xml
        param-value>
    context-param>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
复制代码

 

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

复制代码
 
    <context-param>
        <param-name>contextClassparam-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        param-value>
    context-param>

    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>com.example.Car,com.example.Bossparam-value>
    context-param>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

你可能感兴趣的:(spring)