面试知识点1:Tomcat+Spring中有几个ApplicationContext?它们的关系是什么样的?

Tomcat+Spring的配置环境下,系统中有几个常用的Context,它们之间的关系是什么样子的?

我们以只有1个Servlet的简单情况为例,一般涉及到3个配置文件:web.xml,applicationContext.xml,xxx-servlet.xml。

web.xml:
<context-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:/applicationContext.xml</param-value>
</context-param>
<listener>
         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
         <servlet-name>xxx</servlet-name>
         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
         <servlet-name>xxx</servlet-name>
         <url-pattern>*.html</url-pattern>
</servlet-mapping>

在这种情况下,系统会生成2个ApplicationContext,确切的说是2个WebApplicationContext:

一)ROOT ApplicationContext

在Tomcat启动时,通过注册的监听器ContextLoaderListener,Spring初始化WebApplicationContext并保存到ServletContext中,初始化使用的配置文件位置由contextConfigLocation参数确定。该Context为整个框架中的ROOT Context,其他的Context都会作为其子节点或子孙节点进行关联。

WebApplicationContext和ServletContext互相保存对方的引用:

//保存到ServletContext中
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,this.context);

       //保存ServletContext
       wac.setServletContext(sc);

二)xxx ApplicationContext

Tomcat生成xxx Servlet时,DispatcherServlet会使用xxx-servlet.xml(除非显示指定其他文件)初始化WebApplicationContext,将其父节点设为ROOT Context,并保存到ServletContext中。

 

在createWebApplicationContext()方法中,设置父节点:

                   wac.setParent(parent);

 

在configureAndRefreshWebApplicationContext()方法中保存ServletContext:

                   wac.setServletContext(getServletContext());
                   wac.setServletConfig(getServletConfig());


 在initWebApplicationContext()方法中将自己保存到ServletContext中:

			// Publish the context as a servlet context attribute.
			String attrName = getServletContextAttributeName();
			getServletContext().setAttribute(attrName, wac);

ServletContext、ROOT Context和xxx Context三者引用之间的关系如下:

 

获取的方法:

1.      ServletContext:

无论是在ROOT还是xxx Context中,都可以通过WebApplicationContext. getServletContext();

2.      ROOT Context:

该Context是” org.springframework.web.context. WebApplicationContext. ROOT”为Key保存在ServletContext中。可以使用Spring提供的工具类方法获取:

WebApplicationContextUtils.getWebApplicationContext(ServletContextsc)

 

在xxx Context中可以通过getParent得到ROOT Context。

3.      xxx Context:

该Context是以” org.springframework.web.servlet.FrameworkServlet.CONTEXT.xxx”为KEY(xxx为web.xml中定义的Servlet名称),保存在ServletContext中。可以使用Spring提供的工具类方法获取:

WebApplicationContextUtils.getWebApplicationContext(ServletContextsc, String attrName)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值