详解springMVC容器加载源码分析
springmvc是一个基于servlet容器的轻量灵活的mvc框架,在它整个请求过程中,为了能够灵活定制各种需求,所以提供了一系列的组件完成整个请求的映射,响应等等处理。这里我们来分析下springmvc的源码。
首先,spring提供了一个处理所有请求的servlet,这个servlet实现了servlet的接口,就是dispatcherservlet。把它配置在web.xml中,并且处理我们在整个mvc中需要处理的请求,一般如下配置:
<servlet> <servlet-name>spring-servlet</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param> <param-name>contextconfiglocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-servlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
dispatcherservlet也继承了frameworkservlet抽象类,这个抽象类为整个servlet的处理提供了spring容器的支持,让原本servlet容器的dispatcherservlet拥有能够利用spring容器组件的能力。上面servlet的初始化参数contextconfiglocation就是dispatcherservlet获取spring容器的配置环境。frameworkservlet继承自org.springframework.web.servlet.httpservletbean。httpservletbean实现了servlet容器初始化会调用的init函数。这个init函数会调用frameworkservlet的初始化加载spring容器方法。方法源码:
@override protected final void initservletbean() throws servletexception { getservletcontext().log("initializing spring frameworkservlet '" + getservletname() + "'"); if (this.logger.isinfoenabled()) { this.logger.info("frameworkservlet '" + getservletname() + "': initialization started"); } long starttime = system.currenttimemillis(); try { // 初始化spring-servlet容器 this.webapplicationcontext = initwebapplicationcontext(); initframeworkservlet(); } catch (servletexception ex) { this.logger.error("context initialization failed", ex); throw ex; } catch (runtimeexception ex) { this.logger.error("context initialization failed", ex); throw ex; } if (this.logger.isinfoenabled()) { long elapsedtime = system.currenttimemillis() - starttime; this.logger.info("frameworkservlet '" + getservletname() + "': initialization completed in " + elapsedtime + " ms"); } }
可以看到这里就触发了spring的对web支持的容器初始化,这里使用的容器为webapplicationcontext.接下来我们就来分析一下整个容器的初始化过程:
protected webapplicationcontext initwebapplicationcontext() { // 查看是否在servlet上下文有所有容器需要继承的根web容器 webapplicationcontext rootcontext = webapplicationcontextutils.getwebapplicationcontext(getservletcontext()); webapplicationcontext wac = null; // 如果容器已经加载 if (this.webapplicationcontext != null) { // a context instance was injected at construction time -> use it wac = this.webapplicationcontext; if (wac instanceof configurablewebapplicationcontext) { 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, etc if (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 id wac = findwebapplicationcontext(); } if (wac == null) { // 创建容器 wac = 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 + "]"); } } return wac; }
如果已经有容器被创建那就初始化。否则创建容器,创建逻辑:
protected webapplicationcontext 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 new applicationcontextexception( "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()); // 这里是获取配置文件和完成初始化web容器的入口 configureandrefreshwebapplicationcontext(wac); return wac; }
这里完成了 web容器的相关准备工作,开始正式读取配置文件加载和初始化容器。
protected void configureandrefreshwebapplicationcontext(configurablewebapplicationcontext wac) { // 给容器设置一个id 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 information if (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, new contextrefreshlistener())); // 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 #refresh configurableenvironment env = wac.getenvironment(); if (env instanceof configurablewebenvironment) { ((configurablewebenvironment) env).initpropertysources(getservletcontext(), getservletconfig()); } /* 这里在容器被激活后, 并且容器还没完成初始化之前可以对容器的相关配置做一些修改, 默认给了空实现, 这里子类可以去重写,能够获得在容器初始化之前做 一些处理*/ postprocesswebapplicationcontext(wac); // 这里讲容器的初始化信息放到一个列表 applyinitializers(wac); // 这里就开始web容器的初始化 wac.refresh(); }
容器的初始化在abstractapplicationcontext,无论是其他的容器,最终都会调用到refresh()函数,这个函数基本定义了整个容器初始化的整个脉络,这里不展开讲,本博客之后应该会详细分析这块的逻辑,这里大概的注释一下每一个函数完成的操作:
public void refresh() throws beansexception, illegalstateexception { synchronized (this.startupshutdownmonitor) { // 这里主要加载了容器当中一些从其他配置文件读取的变量 preparerefresh(); // 获取容器本身 configurablelistablebeanfactory beanfactory = obtainfreshbeanfactory(); // 这里完成一些基础组件的依赖 preparebeanfactory(beanfactory); try { // 添加 容器初始化之前的前置处理 postprocessbeanfactory(beanfactory); // 调用 前置处理器,其中包含invokebeandefinitionregistrypostprocessors与invokebeanfactorypostprocessors两类前置处理器的调用 invokebeanfactorypostprocessors(beanfactory); // 注册bean被创建之前的前置处理器 registerbeanpostprocessors(beanfactory); // 初始化容器的编码源 initmessagesource(); // 初始化一些事件监听器 initapplicationeventmulticaster(); // initialize other special beans in specific context subclasses. onrefresh(); // 注册容器监听器 registerlisteners(); // 初始化所有非懒加载的beans finishbeanfactoryinitialization(beanfactory); // last step: 事件通知关心容器加载的相关组件 finishrefresh(); } // 部分代码省略 } } }
自此加载完毕核心容器,然后回到framewordservlet的initwebapplicationcontext函数,在调用createwebapplicationcontext完成一系列上面的操作之后,需要mvc servlet组件,入口就是onrefresh(applocationcontext context)方法。它会调用另一个方法initstrategies(applicationcontext context)。该方法如下:
protected void initstrategies(applicationcontext context) { initmultipartresolver(context); initlocaleresolver(context); initthemeresolver(context); // 获取所有的requestmappings inithandlermappings(context); // 不同handler的适配器 inithandleradapters(context); // 异常解析器 inithandlerexceptionresolvers(context); initrequesttoviewnametranslator(context); initviewresolvers(context); initflashmapmanager(context); }
这里我们重点讲解inithandlermappings与inithandleradapters函数,因为这两个是处理servlet请求的入口。
在spring mvc中任何类都可以处理request请求,因为dispacherservlet也是实现了httpservlet的接口,所以处理请求也是doservice里。doservice会将请求交给dodispatcher函数处理。然后dodispacher的源码:
protected void dodispatch(httpservletrequest request, httpservletresponse response) throws exception { httpservletrequest processedrequest = request; handlerexecutionchain mappedhandler = null; boolean multipartrequestparsed = false; webasyncmanager asyncmanager = webasyncutils.getasyncmanager(request); try { modelandview mv = null; exception dispatchexception = null; try { processedrequest = checkmultipart(request); multipartrequestparsed = (processedrequest != request); // 这里获取当前请求的处理handler mappedhandler = gethandler(processedrequest, false); if (mappedhandler == null || mappedhandler.gethandler() == null) { nohandlerfound(processedrequest, response); return; } /* 因为handler可以是任何类, 但是我们的dispacherservlet需要一个统一的处理接口,这个接口就是handleradapter, 不同的handlermapping可以获取到各种各样的handler, 这个handler最后都必须得到handleradapter的支持才能被dispacherservlet所调用。 扩充一个新的handlermapping只需要添加一个新的handleradatper即可,有点抽象工厂模式的味道*/ handleradapter ha = gethandleradapter(mappedhandler.gethandler()); // process last-modified header, if supported by the handler. string method = request.getmethod(); boolean isget = "get".equals(method); if (isget || "head".equals(method)) { long lastmodified = ha.getlastmodified(request, mappedhandler.gethandler()); if (logger.isdebugenabled()) { logger.debug("last-modified value for [" + getrequesturi(request) + "] is: " + lastmodified); } if (new servletwebrequest(request, response).checknotmodified(lastmodified) && isget) { return; } } if (!mappedhandler.applyprehandle(processedrequest, response)) { return; } // actually invoke the handler. mv = ha.handle(processedrequest, response, mappedhandler.gethandler()); if (asyncmanager.isconcurrenthandlingstarted()) { return; } applydefaultviewname(request, mv); mappedhandler.applyposthandle(processedrequest, response, mv); } catch (exception ex) { dispatchexception = ex; } processdispatchresult(processedrequest, response, mappedhandler, mv, dispatchexception); } catch (exception ex) { triggeraftercompletion(processedrequest, response, mappedhandler, ex); } catch (error err) { triggeraftercompletionwitherror(processedrequest, response, mappedhandler, err); } finally { if (asyncmanager.isconcurrenthandlingstarted()) { // instead of posthandle and aftercompletion if (mappedhandler != null) { mappedhandler.applyafterconcurrenthandlingstarted(processedrequest, response); } } else { // clean up any resources used by a multipart request. if (multipartrequestparsed) { cleanupmultipart(processedrequest); } } } }
但是我们发现获取到的handler并不是object而是一个handlerexecutionchain,这个类可以进去查看发现是一堆拦截器和一个handler,主要就是给每一个请求一个前置处理的机会,这里值得一提的是一般来说拦截器和过滤器的区别就是拦截器可以终止后续执行流程,而过滤器一般不终止。过滤器一般是容器级别的,这个handler前置拦截器可以做到更细级别的控制,例如过滤器只定义了init和dofilter,但是这个handler拦截器定义了prehandle和posthandle还有aftercompletion函数,不难理解分别对应不同请求阶段的拦截粒度,更加灵活。
获取处理handler的gethandler代码:
protected handlerexecutionchain gethandler(httpservletrequest request) throws exception { // 这里获取多个映射方式,一旦找到合适的处理请求的handler即返回 for (handlermapping hm : this.handlermappings) { if (logger.istraceenabled()) { logger.trace( "testing handler map [" + hm + "] in dispatcherservlet with name '" + getservletname() + "'"); } // handlerexecutionchain包含了 handlerexecutionchain handler = hm.gethandler(request); if (handler != null) { return handler; } } return null; }
handleradapter处理后返回统一被封装成modelandview对象,这个就是包含试图和数据的对象,在经过适当的处理:
processdispatchresult(httpservletrequest request, httpservletresponse response, handlerexecutionchain mappedhandler, modelandview mv, exception exception)
将页面与返回的数据返回给浏览器完成整个请求过程。以上就是springmvc大概的启动过程和请求的处理过程,之后本博客还会陆续分析核心的spring源码,博主一直认为精读著名框架源码是在短时间提升代码能力的捷径,因为这些*包含太多设计思想和细小的代码规范,这些读多了都会潜移默化的形成一种本能的东西。设计模式也不断贯穿其中。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。