做项目时碰到Controller不能使用aop进行拦截,从网上搜索得知:使用spring mvc 启动了两个context:applicationContext 和WebapplicationContext。

首先我们来了解applicationContext 和WebapplicationContext区别和联系吧

1. ApplicationContext和WebApplicationContext是继承关系

/*** Interface to provide configuration for a web application. This is read-only while* the application is running, but may be reloaded if the implementation supports this.** <p>This interface adds a {@codegetServletContext()} method to the generic* ApplicationContext interface, and defines a well-known application attribute name* that the root context must be bound to in the bootstrap process.** <p>Like generic application contexts, web application contexts are hierarchical.* There is a single root context per application, while each servlet in the application* (including a dispatcher servlet in the MVC framework) has its own child context.** <p>In addition to standard application context lifecycle capabilities,* WebApplicationContext implementations need to detect {@linkServletContextAware}* beans and invoke the {@codesetServletContext} method accordingly.*/
public interface WebApplicationContext extends ApplicationContext {

2. ContextLoaderListener 创建基于web的应用 applicationContext 并将它放入到ServletContext. applicationContext加载或者卸载spring管理的beans。在structs和spring mvc的控制层都是这样使用的。3. DispatcherServlet创建自己的WebApplicationContext并管理这个WebApplicationContext里面的 handlers/controllers/view-resolvers.

4. 当ContextLoaderListener和DispatcherServlet一起使用时, ContextLoaderListener 先创建一个根applicationContext,然后DispatcherSerlvet创建一个子applicationContext并且绑定到根applicationContext。

首先来看看web.xml的定义:

一般的web应用,通过ContextLoaderListener监听,ContextLoaderListener中加载的context成功后,spring 将 applicationContext存放在ServletContext中key值为"org.springframework.web.context.WebApplicationContext.ROOT"的attribute中。

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:conf/applicationContext*.xml</param-value>
</context-param>  

DispatcherServlet加载的context成功后,会将applicationContext存放在org.springframework.web.servlet.FrameworkServlet.CONTEXT. + (servletName)的attribute中。

<servlet><servlet-name>mvcServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:conf/spring-dispatcher-servlet.xml</param-value></init-param><load-on-startup>1</load-on-startup>
</servlet>

当然,如果没有指定*servlet.xml 配置,则默认使用DispatcherServlet的默认配置DispatcherServlet.properties

# Default implementation classes for DispatcherServlet's strategy interfaces.
# Used as fallback when no matching beans are found in the DispatcherServlet context.
# Not meant to be customized by application developers.org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolverorg.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolverorg.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMappingorg.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapterorg.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,\org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolverorg.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslatororg.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolverorg.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager

简单的来说:spring bean的管理在applicationContext中,ContextLoaderListener的作用:

1. 将applicationContext的生命周期和servletContext的生命周期联系到一起。

2. 自动管理applicationContext的创建,ContextLoaderListener 给我们提供了一个便利,不用显式的去创建applicationContext。

DispatcherServlet 相关bean的管理在WebApplicationContext,ServletContextListener创建WebApplicationContext,WebApplicationContext可以访问ServletContext/ServletContextAware这些bean,还可以访问getServletContext方法。

正式的官方文档:

A web application can define any number of DispatcherServlets. Each servlet will operate in its own namespace, loading its own application context with mappings, handlers, etc. Only the root application context as loaded by ContextLoaderListener, ifany, will be shared. As of Spring3.1, DispatcherServlet may now be injected with a web application context, rather than creating its own internally. This is useful in Servlet 3.0+ environments, which support programmatic registration of servlet instances. 

在一个web应用中使用多个DispatcherServlet,每个servlet通过自己的命名空间来获取自己的webapplicationContext,然后加载此applicationContext里面的hangdlerMapping,hangdlerAdapter等等。ContextLoaderListener加载根application,所有子applicationContext共享根applicationContext。

从版本3.1 后,spring 支持将DispatcherServlet注入到根applicationContext,而不用创建自己的webapplicationContext,这主要为支持servlet 3.0 以上版本环境的要求,因为servlet 3.0 以上版本支持使用编程的方式来注册servlet实例。

spring支持使用多层层次applicationContext,通常我们使用两层结构就够了。

接下来,通过深入源代码层来探究WebApplicationContext是如何创建的?

1. DispatcherServlet的初始化过程使用到applicationContext。

我们知道DispatcherServlet直接继承自FrameworkServlet,而FrameworkServlet又继承了HttpServletBean和 ApplicationContextAware。

2. FrameworkServlet实现了ApplicationContextAware接口的setApplicationContext()方法,可知DispatcherServlet的applicationContext来自FrameworkServlet。

    /*** Called by Spring via {@linkApplicationContextAware} to inject the current* application context. This method allows FrameworkServlets to be registered as* Spring beans inside an existing {@linkWebApplicationContext} rather than* {@link#findWebApplicationContext() finding} a* {@linkorg.springframework.web.context.ContextLoaderListener bootstrapped} context.* <p>Primarily added to support use in embedded servlet containers.*@since4.0*/@Overridepublic voidsetApplicationContext(ApplicationContext applicationContext) {if (this.webApplicationContext == null && applicationContext instanceofWebApplicationContext) {this.webApplicationContext =(WebApplicationContext) applicationContext;this.webApplicationContextInjected = true;}}

3. FrameworkServlet的setApplicationContext()方法中WebApplicationContext是如何实例化的呢?

FrameworkServlet继承自HttpServletBean,HttpServletBean的初始化方法:

/*** Map config parameters onto bean properties of this servlet, and* invoke subclass initialization.*@throwsServletException if bean properties are invalid (or required* properties are missing), or if subclass initialization fails.*/@Overridepublic final void init() throwsServletException {if(logger.isDebugEnabled()) {logger.debug("Initializing servlet '" + getServletName() + "'");}//Set bean properties from init parameters.try{PropertyValues pvs= new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);BeanWrapper bw= PropertyAccessorFactory.forBeanPropertyAccess(this);ResourceLoader resourceLoader= newServletContextResourceLoader(getServletContext());bw.registerCustomEditor(Resource.class, newResourceEditor(resourceLoader, getEnvironment()));initBeanWrapper(bw);bw.setPropertyValues(pvs,true);}catch(BeansException ex) {logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);throwex;}// Let subclasses do whatever initialization they like.initServletBean();if(logger.isDebugEnabled()) {logger.debug("Servlet '" + getServletName() + "' configured successfully");}}

FrameworkServlet 实现了initServletBean();

    /*** Overridden method of {@linkHttpServletBean}, invoked after any bean properties* have been set. Creates this servlet's WebApplicationContext.*/@Overrideprotected final void initServletBean() throwsServletException {getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");if (this.logger.isInfoEnabled()) {this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");}long startTime =System.currentTimeMillis();try{this.webApplicationContext =initWebApplicationContext();initFrameworkServlet();}catch(ServletException ex) {this.logger.error("Context initialization failed", ex);throwex;}catch(RuntimeException ex) {this.logger.error("Context initialization failed", ex);throwex;}if (this.logger.isInfoEnabled()) {long elapsedTime = System.currentTimeMillis() -startTime;this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +elapsedTime+ " ms");}}

最终追踪到FrameworkServlet 的initWebApplicationContext()方法

/*** Initialize and publish the WebApplicationContext for this servlet.* <p>Delegates to {@link#createWebApplicationContext} for actual creation* of the context. Can be overridden in subclasses.*@returnthe WebApplicationContext instance*@see#FrameworkServlet(WebApplicationContext)*@see#setContextClass*@see#setContextConfigLocation*/protectedWebApplicationContext initWebApplicationContext() {WebApplicationContext rootContext=WebApplicationContextUtils.getWebApplicationContext(getServletContext());WebApplicationContext wac= null;if (this.webApplicationContext != null) {//A context instance was injected at construction time -> use itwac = this.webApplicationContext;if (wac instanceofConfigurableWebApplicationContext) {ConfigurableWebApplicationContext cwac=(ConfigurableWebApplicationContext) wac;if (!cwac.isActive()) {//The context has not yet been refreshed -> provide services such as//setting the parent context, setting the application context id, etcif (cwac.getParent() == null) {//The context instance was injected without an explicit parent -> set//the root application context (if any; may be null) as the parent
cwac.setParent(rootContext);}configureAndRefreshWebApplicationContext(cwac);}}}if (wac == null) {//No context instance was injected at construction time -> see if one//has been registered in the servlet context. If one exists, it is assumed//that the parent context (if any) has already been set and that the//user has performed any initialization such as setting the context idwac =findWebApplicationContext();}if (wac == null) {//No context instance is defined for this servlet -> create a local onewac =createWebApplicationContext(rootContext);}if (!this.refreshEventReceived) {//Either the context is not a ConfigurableApplicationContext with refresh//support or the context injected at construction time had already been//refreshed -> trigger initial onRefresh manually here.
onRefresh(wac);}if (this.publishContext) {//Publish the context as a servlet context attribute.String attrName =getServletContextAttributeName();getServletContext().setAttribute(attrName, wac);if (this.logger.isDebugEnabled()) {this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +"' as ServletContext attribute with name [" + attrName + "]");}}returnwac;}

我们来分析整个流程吧:

1. 获取根applicationContext。

        WebApplicationContext rootContext =WebApplicationContextUtils.getWebApplicationContext(getServletContext());/*** Find the root {@linkWebApplicationContext} for this web app, typically* loaded via {@linkorg.springframework.web.context.ContextLoaderListener}.* <p>Will rethrow an exception that happened on root context startup,* to differentiate between a failed context startup and no context at all.*@paramsc ServletContext to find the web application context for*@returnthe root WebApplicationContext for this web app, or {@codenull} if none*@seeorg.springframework.web.context.WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE*/public staticWebApplicationContext getWebApplicationContext(ServletContext sc) {returngetWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);}/*** Find a custom {@linkWebApplicationContext} for this web app.*@paramsc ServletContext to find the web application context for*@paramattrName the name of the ServletContext attribute to look for*@returnthe desired WebApplicationContext for this web app, or {@codenull} if none*/public staticWebApplicationContext getWebApplicationContext(ServletContext sc, String attrName) {Assert.notNull(sc,"ServletContext must not be null");Object attr= sc.getAttribute(attrName);if (attr == null) {return null;}if (attr instanceofRuntimeException) {throw(RuntimeException) attr;}if (attr instanceofError) {throw(Error) attr;}if (attr instanceofException) {throw newIllegalStateException((Exception) attr);}if (!(attr instanceofWebApplicationContext)) {throw new IllegalStateException("Context attribute is not of type WebApplicationContext: " +attr);}return(WebApplicationContext) attr;}

2. 判断webapplicationContext是否存在?存在的话就重利用该webapplicationContext

    protected voidconfigureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {if(ObjectUtils.identityToString(wac).equals(wac.getId())) {//The application context id is still set to its original default value//-> assign a more useful id based on available informationif (this.contextId != null) {wac.setId(this.contextId);}else{//Generate default id...wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +ObjectUtils.getDisplayString(getServletContext().getContextPath())+ "/" +getServletName());}}wac.setServletContext(getServletContext());wac.setServletConfig(getServletConfig());wac.setNamespace(getNamespace());wac.addApplicationListener(new SourceFilteringListener(wac, newContextRefreshListener()));//The wac environment's #initPropertySources will be called in any case when the context//is refreshed; do it eagerly here to ensure servlet property sources are in place for//use in any post-processing or initialization that occurs below prior to #refreshConfigurableEnvironment env =wac.getEnvironment();if (env instanceofConfigurableWebEnvironment) {((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());}postProcessWebApplicationContext(wac);applyInitializers(wac);wac.refresh();}

不存在的话,根据配置的属性名去查询:

    /*** Retrieve a {@codeWebApplicationContext} from the {@codeServletContext}* attribute with the {@link#setContextAttribute configured name}. The* {@codeWebApplicationContext} must have already been loaded and stored in the* {@codeServletContext} before this servlet gets initialized (or invoked).* <p>Subclasses may override this method to provide a different* {@codeWebApplicationContext} retrieval strategy.*@returnthe WebApplicationContext for this servlet, or {@codenull} if not found*@see#getContextAttribute()*/protectedWebApplicationContext findWebApplicationContext() {String attrName=getContextAttribute();if (attrName == null) {return null;}WebApplicationContext wac=WebApplicationContextUtils.getWebApplicationContext(getServletContext(), attrName);if (wac == null) {throw new IllegalStateException("No WebApplicationContext found: initializer not registered?");}returnwac;}

3. 如果还查询不到WebapplicationContext,那么就创建一个新的WebapplicationContext,并绑定到root WebapplicationContext上:

/*** Instantiate the WebApplicationContext for this servlet, either a default* {@linkorg.springframework.web.context.support.XmlWebApplicationContext}* or a {@link#setContextClass custom context class}, if set.* <p>This implementation expects custom contexts to implement the* {@linkorg.springframework.web.context.ConfigurableWebApplicationContext}* interface. Can be overridden in subclasses.* <p>Do not forget to register this servlet instance as application listener on the* created context (for triggering its {@link#onRefresh callback}, and to call* {@linkorg.springframework.context.ConfigurableApplicationContext#refresh()}* before returning the context instance.*@paramparent the parent ApplicationContext to use, or {@codenull} if none*@returnthe WebApplicationContext for this servlet*@seeorg.springframework.web.context.support.XmlWebApplicationContext*/protectedWebApplicationContext createWebApplicationContext(ApplicationContext parent) {Class<?> contextClass =getContextClass();if (this.logger.isDebugEnabled()) {this.logger.debug("Servlet with name '" + getServletName() +"' will try to create custom WebApplicationContext context of class '" +contextClass.getName()+ "'" + ", using parent context [" + parent + "]");}if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {throw newApplicationContextException("Fatal initialization error in servlet with name '" + getServletName() +"': custom WebApplicationContext class [" + contextClass.getName() +"] is not of type ConfigurableWebApplicationContext");}ConfigurableWebApplicationContext wac=(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);wac.setEnvironment(getEnvironment());wac.setParent(parent);wac.setConfigLocation(getContextConfigLocation());configureAndRefreshWebApplicationContext(wac);returnwac;}

4. 将子applicationContext发布到servlet context上。

        if (this.publishContext) {//Publish the context as a servlet context attribute.String attrName =getServletContextAttributeName();getServletContext().setAttribute(attrName, wac);if (this.logger.isDebugEnabled()) {this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +"' as ServletContext attribute with name [" + attrName + "]");}}

/**
* Return the ServletContext attribute name for this servlet's WebApplicationContext.
* <p>The default implementation returns
* {@code SERVLET_CONTEXT_PREFIX + servlet name}.
* @see #SERVLET_CONTEXT_PREFIX
* @see #getServletName
*/
public String getServletContextAttributeName() {
return SERVLET_CONTEXT_PREFIX + getServletName();
}

/**
* Prefix for the ServletContext attribute for the WebApplicationContext.
* The completion is the servlet name.
*/
public static final String SERVLET_CONTEXT_PREFIX = FrameworkServlet.class.getName() + ".CONTEXT.";

最后,ContextLoaderListener启动时如何产生applicationContext呢?

见参考我的这篇文章:http://www.cnblogs.com/davidwang456/archive/2013/03/12/2956125.html

小结:

我们就以FrameworkServlet的官方说明来结束吧。没有比它更合适的!希望你喜欢。

public abstract classFrameworkServletextendsHttpServletBeanimplements ApplicationContextAwareBase servlet for Spring's web framework. Provides integration with a Spring application context, in a JavaBean-based overall solution.
This classoffers the following functionality: Manages a WebApplicationContext instance per servlet. The servlet's configuration is determined by beans in the servlet's namespace.
Publishes events on request processing, whether or not a request is successfully handled.
Subclasses must implement doService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) to handle requests. Becausethis extends HttpServletBean rather than HttpServlet directly, bean properties are automatically mapped onto it. Subclasses can override initFrameworkServlet() forcustom initialization. Detects a"contextClass" parameter at the servlet init-param level, falling back to the default context class, XmlWebApplicationContext, if not found. Note that, with the default FrameworkServlet, a custom context classneeds to implement the ConfigurableWebApplicationContext SPI. Accepts an optional"contextInitializerClasses" servlet init-param that specifies one or more ApplicationContextInitializer classes. The managed web application context will be delegated to these initializers, allowing for additional programmatic configuration, e.g. adding property sources or activating profiles against the context's environment. See also ContextLoader which supports a "contextInitializerClasses" context-param with identical semantics for the "root" web application context.
Passes a"contextConfigLocation" servlet init-param to the context instance, parsing it into potentially multiple file paths which can be separated by any number of commas and spaces, like "test-servlet.xml, myServlet.xml". If not explicitly specified, the context implementation is supposed to build a defaultlocation from the namespace of the servlet. Note: Incase of multiple config locations, later bean definitions will override ones defined in earlier loaded files, at least when using Spring's default ApplicationContext implementation. This can be leveraged to deliberately override certain bean definitions via an extra XML file.
Thedefault namespace is "'servlet-name'-servlet", e.g. "test-servlet" for a servlet-name "test" (leading to a "/WEB-INF/test-servlet.xml" default location with XmlWebApplicationContext). The namespace can also be set explicitly via the "namespace" servlet init-param. As of Spring3.1, FrameworkServlet may now be injected with a web application context, rather than creating its own internally. This is useful in Servlet 3.0+ environments, which support programmatic registration of servlet instances. See FrameworkServlet(WebApplicationContext) Javadoc for details.

参考资料:

http://starscream.iteye.com/blog/1107036

http://www.softwarevol.com/en/tutorial/Spring-ContextLoaderListener-And-DispatcherServlet-Concepts

转载于:https://www.cnblogs.com/davidwang456/p/4122842.html

spring mvc DispatcherServlet详解之前传---FrameworkServlet相关推荐

  1. spring mvc DispatcherServlet详解之前传---前端控制器架构

    前端控制器是整个MVC框架中最为核心的一块,它主要用来拦截符合要求的外部请求,并把请求分发到不同的控制器去处理,根据控制器处理后的结果,生成相应的响应发送到客户端.前端控制器既可以使用Filter实现 ...

  2. spring mvc DispatcherServlet详解前传---HttpServletBean类

    从上章里我们已经看到: DispatcherServlet extends FrameworkServlet FrameworkServlet extends HttpServletBean impl ...

  3. spring mvc DispatcherServlet详解之一---处理请求深入解析

    要深入理解spring mvc的工作流程,就需要先了解spring mvc的架构: 从上图可以看到 前端控制器DispatcherServlet在其中起着主导作用,理解了DispatcherServl ...

  4. spring mvc DispatcherServlet详解之三---request通过ModelAndView中获取View实例的过程

    整个spring mvc的架构如下图所示: 上篇文件讲解了DispatcherServlet第二步:通过request从Controller获取ModelAndView.现在来讲解第三步:reques ...

  5. spring mvc DispatcherServlet详解之二---request通过Controller获取ModelAndView过程

    整个spring mvc的架构如下图所示: 上篇文件讲解了DispatcherServlet通过request获取控制器Controller的过程,现在来讲解DispatcherServletDisp ...

  6. spring mvc DispatcherServlet详解之一--request通过HandlerMaping获取控制器Controller过程

    整个spring mvc的架构如下图所示: 现在来讲解DispatcherServletDispatcherServlet的第一步:获取控制器. HandlerMapping HandlerMappi ...

  7. spring mvc DispatcherServlet详解之四---视图渲染过程

    整个spring mvc的架构如下图所示: 现在来讲解DispatcherServletDispatcherServlet的最后一步:视图渲染.视图渲染的过程是在获取到ModelAndView后的过程 ...

  8. spring mvc DispatcherServlet详解之interceptor和filter的区别

    首先我们看一下spring mvc Interceptor的功能及实现: http://wenku.baidu.com/link?url=Mw3GaUhCRMhUFjU8iIDhObQpDcbmmRy ...

  9. spring mvc DispatcherServlet详解之拾忆工具类utils

    DispatcherServlet的静态初始化 /*** Name of the class path resource (relative to the DispatcherServlet clas ...

最新文章

  1. [PHP] - 性能加速 - 开启opcache
  2. 【CV】使用计算机视觉算法检测钢板中的焊接缺陷
  3. wampserver启动报错:1 of 2 services running - 解决篇
  4. WCF技术剖析(卷1)正式出版
  5. python多用户登录_python多用户
  6. Redis基础学习(2)
  7. I/O 多路复用的特点:
  8. pandasql库学习使用之在Python中执行SQL语句
  9. DBeaver 连接 Oracle
  10. vue安装vue-pdf(预览pdf)
  11. 企业出口退税申报系统的Sqlite数据库破解及读写
  12. 常用技术面试题(软件测试)
  13. [渝粤教育] 中央财经大学 宏观经济学 参考 资料
  14. 计算机专业建设会议纪要,智能控制教研室会议纪要6号
  15. julia集 matlab代码,Julia中文手册1.1版本
  16. Android之Material Dialogs详解(非原创)
  17. 如何使用YouTube视频管理器
  18. 信号完整性之铜皮粗糙度
  19. STP的端口状态,BPDU,计时器
  20. 如何注册腾讯云账号(图文教程)?

热门文章

  1. 启动服务错误5拒绝访问_【Go API 开发实战 5】基础1:启动一个最简单的 RESTful API 服务器...
  2. python画旺仔代码_美术生把旺仔牛奶画成抖音网红,看清画的是谁,网友:确认过眼神...
  3. 计算机游戏的作文,玩电脑游戏作文
  4. perl语言入门第七版中文_python和c语言哪个简单
  5. python爬虫,爬取猫眼电影1(正则表达式)
  6. 文件服务器高可用群集,fastDFS文件服务器(三):集群和高可用环境篇
  7. 页面重新加载_Chrome为PWA应用加入了返回和重新加载按钮
  8. lua和python哪个简单_盘点一下lua脚本和python的区别(基础)
  9. oracle ora 00279,ORA-01245、ORA-01547错误的解决
  10. Win10 插入耳机无声问题 解决办法