您的位置:首页 > 编程语言 > Java开发

深入分析Spring 与 Spring MVC容器启动

2017-08-08 20:40 459 查看
Spring经典详解

Spring事务机制详解
Spring配置事务五种方式
关于Spring加载classpath与classpath*的过程剖析
深入分析Spring与SpringMVC容器

Spring系列文章

【第1章Spring概述与结构】1.1Spring起源与概述
【第1章Spring概述与结构】1.2Spring模块与结构
【第2章Spring快速入门】2.1Java应用之HelloWorld
【第2章Spring快速入门】2.2WEB应用之HelloWorld
[【第2章Spring快速入门】2.3Spring三大核心组件]

1SpringMVCWEB配置

SpringFramework本身没有Web功能,
SpringMVC使用WebApplicationContext类扩展ApplicationContext
,使得拥有web功能。那么,SpringMVC是如何在web环境中创建IoC容器呢?web环境中的IoC容器的结构又是什么结构呢?web环境中,SpringIoC容器是怎么启动呢?

以Tomcat为例,在Web容器中使用SpirngMVC,必须进行四项的配置:

修改web.xml,添加servlet定义;
编写servletname-servlet.xml(servletname是在web.xm中配置DispactherServlet时使servlet-name的值)配置;
contextConfigLocation初始化参数、配置ContextLoaderListerner;
Web.xml配置如下:

<!--servlet定义:前端处理器,接受的HTTP请求和转发请求的类-->
<servlet>
<servlet-name>court</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!--court-servlet.xml:定义WebAppliactionContext上下文中的bean-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:court-servlet.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>court</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!--配置contextConfigLocation初始化参数:指定SpringIoC容器需要读取的定义了非web层的Bean(DAO/Service)的XML文件路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/court-service.xml</param-value>
</context-param>

<!--配置ContextLoaderListerner:SpringMVC在Web容器中的启动类,负责SpringIoC容器在Web上下文中的初始化-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

在web.xml配置文件中,有两个主要的配置:
ContextLoaderListener和DispatcherServlet
。同样的关于spring配置文件的相关配置也有两部分:
context-param和DispatcherServlet中的init-param
。那么,这两部分的配置有什么区别呢?它们都担任什么样的职责呢?

在SpringMVC中,
SpringContext是以父子的继承结构存在的
。Web环境中存在一个ROOTContext,这个Context是整个应用的根上下文,是其他context的双亲Context。同时SpringMVC也对应的持有一个独立的Context,它是ROOTContext的子上下文。

对于这样的Context结构在SpringMVC中是如何实现的呢?下面就先从ROOTContext入手,
ROOTContext是在ContextLoaderListener中配置的,ContextLoaderListener读取context-param中的contextConfigLocation指定的配置文件,创建ROOTContext


SpringMVC启动过程大致分为两个过程:

ContextLoaderListener初始化,实例化IoC容器,并将此容器实例注册到ServletContext中;
DispatcherServlet初始化;

2Web容器中Spring根上下文的加载与初始化

Web容器调用contextInitialized方法初始化ContextLoaderListener,在此方法中,
ContextLoaderListener通过调用继承自ContextLoader的initWebApplicationContext方法实例化SpringIoc容器


先看一下WebApplicationContext是如何扩展ApplicationContext来添加对Web环境的支持的。WebApplicationContext接口定义如下:

publicinterfaceWebApplicationContextextendsApplicationContext{
//根上下文在ServletContext中的名称
StringROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE=WebApplicationContext.class.getName()+".ROOT";
//取得web容器的ServletContext
ServletContextgetServletContext();
}


下面看一下ContextLoaderListener中创建context的源码:ContextLoader.java

publicWebApplicationContextinitWebApplicationContext(ServletContextservletContext){
//PS:ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE=WebApplicationContext.class.getName()+".ROOT"根上下文的名称
//PS:默认情况下,配置文件的位置和名称是:DEFAULT_CONFIG_LOCATION="/WEB-INF/applicationContext.xml"
//在整个web应用中,只能有一个根上下文
if(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)!=null){
thrownewIllegalStateException("Cannotinitializecontextbecausethereisalreadyarootapplicationcontextpresent-"+"checkwhetheryouhavemultipleContextLoader*definitionsinyourweb.xml!");
}

Loglogger=LogFactory.getLog(ContextLoader.class);
servletContext.log("InitializingSpringrootWebApplicationContext");
if(logger.isInfoEnabled()){
logger.info("RootWebApplicationContext:initializationstarted");
}
longstartTime=System.currentTimeMillis();

try{
//Storecontextinlocalinstancevariable,toguaranteethat
//itisavailableonServletContextshutdown.
if(this.context==null){
//在这里执行了创建WebApplicationContext的操作
this.context=createWebApplicationContext(servletContext);
}
if(this.contextinstanceofConfigurableWebApplicationContext){
ConfigurableWebApplicationContextcwac=(ConfigurableWebApplicationContext)this.context;
if(!cwac.isActive()){
//Thecontexthasnotyetbeenrefreshed->provideservicessuchas
//settingtheparentcontext,settingtheapplicationcontextid,etc
if(cwac.getParent()==null){
//Thecontextinstancewasinjectedwithoutanexplicitparent->
//determineparentforrootwebapplicationcontext,ifany.
ApplicationContextparent=loadParentContext(servletContext);
cwac.setParent(parent);}
configureAndRefreshWebApplicationContext(cwac,servletContext);
}
}
//PS:将根上下文放置在servletContext中
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,this.context);

ClassLoaderccl=Thread.currentThread().getContextClassLoader();
if(ccl==ContextLoader.class.getClassLoader()){
currentContext=this.context;
}elseif(ccl!=null){
currentContextPerThread.put(ccl,this.context);
}

if(logger.isDebugEnabled()){
logger.debug("PublishedrootWebApplicationContextasServletContextattributewithname["+
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE+"]");
}
if(logger.isInfoEnabled()){
longelapsedTime=System.currentTimeMillis()-startTime;
logger.info("RootWebApplicationContext:initializationcompletedin"+elapsedTime+"ms");
}

returnthis.context;
}catch(RuntimeExceptionex){
logger.error("Contextinitializationfailed",ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,ex);
throwex;
}catch(Errorerr){
logger.error("Contextinitializationfailed",err);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,err);
throwerr;
}
}


再看一下WebApplicationContext对象是如何创建的:ContextLoader.java

protectedWebApplicationContextcreateWebApplicationContext(ServletContextsc,ApplicationContextparent){
//根据web.xml中的配置决定使用何种WebApplicationContext。默认情况下使用XmlWebApplicationContext
//web.xml中相关的配置context-param的名称“contextClass”
Class<?>contextClass=determineContextClass(sc);
if(!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)){
thrownewApplicationContextException("Customcontextclass["+contextClass.getName()+"]isnotoftype["+ConfigurableWebApplicationContext.class.getName()+"]");
}

//实例化WebApplicationContext的实现类
ConfigurableWebApplicationContextwac=(ConfigurableWebApplicationContext)BeanUtils.instantiateClass(contextClass);

//Assignthebestpossibleidvalue.
if(sc.getMajorVersion()==2&&sc.getMinorVersion()<5){
//Servlet<=2.4:resorttonamespecifiedinweb.xml,ifany.
StringservletContextName=sc.getServletContextName();
if(servletContextName!=null){
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX+servletContextName);
}else{
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX);
}
}else{
//Servlet2.5'sgetContextPathavailable!
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX+sc.getContextPath());
}

wac.setParent(parent);
wac.setServletContext(sc);
//设置spring的配置文件
wac.setConfigLocation(sc.getInitParameter(CONFIG_LOCATION_PARAM));
customizeContext(sc,wac);
//spring容器初始化
wac.refresh();
returnwac;
}


ContextLoaderListener构建RootContext时序图:



3SpringMVC对应的上下文加载与初始化

SpringMVC中核心的类是DispatcherServlet
,在这个类中完成Springcontext的加载与创建,并且能够根据SpringContext的内容将请求分发给各个Controller类。
DispatcherServlet继承自HttpServlet
,关于SpringContext的配置文件加载和创建是在
init()
方法中进行的,主要的调用顺序是
init-->initServletBean-->initWebApplicationContext


先来看一下initWebApplicationContext的实现:FrameworkServlet.java

protectedWebApplicationContextinitWebApplicationContext(){
//先从web容器的ServletContext中查找WebApplicationContext
WebApplicationContextwac=findWebApplicationContext();
if(wac==null){
//Nofixedcontextdefinedforthisservlet-createalocalone.
//从ServletContext中取得根上下文
WebApplicationContextparent=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
//创建SpringMVC的上下文,并将根上下文作为起双亲上下文
wac=createWebApplicationContext(parent);
}

if(!this.refreshEventReceived){
//ApparentlynotaConfigurableApplicationContextwithrefreshsupport:
//triggeringinitialonRefreshmanuallyhere.
onRefresh(wac);
}

if(this.publishContext){
//Publishthecontextasaservletcontextattribute.
//取得context在ServletContext中的名称
StringattrName=getServletContextAttributeName();
//将SpringMVC的Context放置到ServletContext中
getServletContext().setAttribute(attrName,wac);
if(this.logger.isDebugEnabled()){
this.logger.debug("PublishedWebApplicationContextofservlet'"+getServletName()+"'asServletContextattributewithname["+attrName+"]");
}
}
returnwac;
}


通过initWebApplicationContext方法的调用,
创建了DispatcherServlet对应的context,并将其放置到ServletContext中
,这样就完成了在web容器中构建SpringIoC容器的过程。

DispatcherServlet创建context时序图:



DispatcherServlet初始化的大体流程:



控制器DispatcherServlet的类图及继承关系:



4Spring中DispacherServlet、WebApplicationContext、ServletContext的关系

要想很好理解这三个上下文的关系,需要先熟悉Spring是怎样在web容器中启动起来的。Spring的启动过程其实就是其IOC容器的启动过程,对于web程序,IOC容器启动过程即是建立上下文的过程。

Spring的启动过程:

首先,对于一个web应用,其部署在web容器中,
web容器提供其一个全局的上下文环境,这个上下文就是ServletContext
,其为后面的springIoC容器提供宿主环境;

其次,
在web.xml中会提供有contextLoaderListener
。在web容器启动时,会触发容器初始化事件,此时contextLoaderListener会监听到这个事件,其contextInitialized方法会被调用,
在这个方法中,spring会初始化一个启动上下文,这个上下文被称为根上下文,即WebApplicationContext,这是一个接口类,确切的说,其实际的实现类是XmlWebApplicationContext。
这个就是spring的IoC容器,其对应的Bean定义的配置由web.xml中的context-param标签指定。在这个IoC容器初始化完毕后,spring以WebApplicationContext.ROOTWEBAPPLICATIONCONTEXTATTRIBUTE为属性Key,将其存储到ServletContext中,便于获取;

再次,contextLoaderListener监听器初始化完毕后,开始初始化web.xml中配置的Servlet,这个servlet可以配置多个,以最常见的DispatcherServlet为例,这个servlet实际上是一个标准的前端控制器,用以转发、匹配、处理每个servlet请求。
DispatcherServlet上下文在初始化的时候会建立自己的IoC上下文,用以持有springmvc相关的bean
。在建立DispatcherServlet自己的IoC上下文时,会利用WebApplicationContext.ROOTWEBAPPLICATIONCONTEXTATTRIBUTE先从ServletContext中获取之前的根上下文(即WebApplicationContext)作为自己上下文的parent上下文。有了这个parent上下文之后,再初始化自己持有的上下文。这个DispatcherServlet初始化自己上下文的工作在其initStrategies方法中可以看到,大概的工作就是初始化处理器映射、视图解析等。
这个servlet自己持有的上下文默认实现类也是mlWebApplicationContext。初始化完毕后,spring以与servlet的名字相关(此处不是简单的以servlet名为Key,而是通过一些转换,具体可自行查看源码)的属性为属性Key,也将其存到ServletContext中,以便后续使用。这样每个servlet就持有自己的上下文,即拥有自己独立的bean空间,同时各个servlet共享相同的bean,即根上下文(第2步中初始化的上下文)定义的那些bean


在Web容器(比如Tomcat)中配置Spring时,你可能已经司空见惯于web.xml文件中的以下配置代码:

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

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

<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
以上配置
首先会在ContextLoaderListener中通过<context-param>中的applicationContext.xml创建一个ApplicationContext
,再将这个ApplicationContext塞到ServletContext里面,通过ServletContext的setAttribute方法达到此目的,在ContextLoaderListener的源代码中,我们可以看到这样的代码:

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,this.context);

以上由ContextLoaderListener创建的ApplicationContext是共享于整个Web应用程序的,而你可能早已经知道,
DispatcherServlet会维持一个自己的ApplicationContext,默认会读取/WEB-INFO/<dispatcherServletName>-servlet.xml文件
,而也可以重新配置:

<servlet>
<servlet-name>
customConfiguredDispacherServlet
</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>
contextConfigLocation
</param-name>
<param-value>
/WEB-INF/dispacherServletContext.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

问题是:以上两个ApplicationContext的关系是什么,它们的作用作用范围分别是什么,它们的用途分别是什么?

ContextLoaderListener中创建ApplicationContext主要用于整个Web应用程序需要共享的一些组件
,比如DAO,数据库的ConnectionFactory等。而
由DispatcherServlet创建的ApplicationContext主要用于和该Servlet相关的一些组件
,比如Controller、ViewResovler等。

对于作用范围而言,
在DispatcherServlet中可以引用由ContextLoaderListener所创建的ApplicationContext
,而反过来不行。

在Spring的具体实现上,这两个ApplicationContext都是通过ServletContext的setAttribute方法放到ServletContext中的。但是,
ContextLoaderListener会先于DispatcherServlet创建ApplicationContext,DispatcherServlet在创建ApplicationContext时会先找到由ContextLoaderListener所创建的ApplicationContext,再将后者的ApplicationContext作为参数传给DispatcherServlet的ApplicationContext的setParent()方法
,在Spring源代码中,你可以在FrameServlet.java中找到如下代码:

wac.setParent(parent);

其中,
wac即为由DisptcherServlet创建的ApplicationContext,而parent则为有ContextLoaderListener创建的ApplicationContext
。此后,框架又会调用ServletContext的setAttribute()方法将wac加入到ServletContext中。

当Spring在执行ApplicationContext的getBean时,
如果在自己context中找不到对应的bean,则会在父ApplicationContext中去找
。这也解释了为什么我们可以在DispatcherServlet中获取到由ContextLoaderListener对应的ApplicationContext中的bean。

转自:https://my.oschina.net/xianggao/blog/523888
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: