SpringMvc父子容器

 
使用监听器listener来加载spring的配置文件:如下

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-beans.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Spring会创建一个WebApplicationContext的上下文,称为父上下文(父容器),key是WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,保存在ServletContext(Servlet上下文全局)中

可以使用Spring提供的工具类取出上下文对象:

WebApplicationContextUtils.getWebApplicationContext(ServletContext);

DispatcherServlet是一个Servlet,可以配置多个,每个DispatcherServlet有一个自己的上下文对象(WebApplictionContext)

称为子上下文(子容器),子上下文可以访问父上下文中的内容,但是父上下文不能范文子上下文中的内容,他也保存在ServletContext中

key是:"org.springframework.web.serrvlet.FrameworkServlet.CONTEXT"+Servlet名字,

当一个Request对象产生是会把这个自上下文对象(WebApplicationContext)保存在Request对象中,

key是DispatcherServlet.class.getName()+"CONTEXT";

可以通过使用工具类获取上下文:RequestContextUtils.getWebApplicationContext(request);

说明:spring并没有限制我们,必须使用父子上下文,我们可以自己决定如何时候如何使用

方案一:使用传统的父子容器的概念:分为controler,service,dao,这些层,service负者业务逻辑并管理事物,dao负责持久

方案二:小项目情况,不需要service,dao,将事物的控制加到controller中,只用springmvc的子容器,web.xml文件中不使用

    listener监听器来加载spring的配置文件,只使用DispatcherServlet来加载spring的配置,不需要父容器,只使用

    DispatcherServlet,事情就简单了,什么麻烦事都没有。(不推荐:只是为了说明sping的容器)

原文地址:https://www.cnblogs.com/ganbo/p/5635185.html