前言

我们一般都知道怎样使用spring来开发web应用后,但对spring的内部实现机制通常不是很明白。这里从源码角度分析下Spring是怎样启动的。在讲spring启动之前,我们先来看看一个web容器是怎样的启动过程、也认识下ServletContextListener和ContextLoaderListener

阅读目录

  • 一、java web容器的启动
  • 二、认识ServletContextListener
  • 三、认识ContextLoaderListener
  • 四、Spring IOC容器的启动

一、java web容器的启动

我们先来看看java web容器是怎样的启动过程

1. 启动一个web项目的时候,web容器会去读取它的配置文件web.xml,读取<context-param>节点。

<context-param>包含了Web应用程序的servlet上下文初始化参数的声明

2.容器创建一个ServletContext(servlet上下文),这个web项目都将共享这个上下文。

3.容器将<context-param>转换为键值对,并交给servletContext。因为listener,filer等在初始化时会用到这些上下文信息,所以要先加载。

4.容器创建<listener>中的类实例,创建监听器。

5.加载filter和servlet。

load- on-startup 元素在web应用启动的时候指定了servlet被加载的顺序,它的值必须是一个整数。

如果它的值是一个负整数或是这个元素不存在,那么容器会在该servlet被调用的时候,加载这个servlet。如果值是正整数或零,容器在配置的时候就加载并初始化这个servlet,容器必须保证值小的先被加载。如果值相等,容器可以自动选择先加载谁。

web.xml 的加载顺序是:context-param -> listener -> filter -> servlet。

Spring工程中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>

其中<listener>标签中定义了spring容器加载器;

二、认识ServletContextListener

上图中是源码中接口ServletContextListener的定义,它定义了处理ServletContextEvent 事件的两个方法contextInitialized()和contextDestroyed()。理.

ServletContextListener能够监听ServletContext对象的生命周期,实际上就是监听Web应用的生命周期。当Servlet容器启动或终止Web应用时,会触发ServletContextEvent事件,该事件由ServletContextListener来处理。

三、认识ContextLoaderListener

上图中是类ContextLoaderListener的定义,它实现了上面的ServletContextListener。

ContextLoaderListener类用来创建Spring application context,并且将application context注册到servletContext里面去。

 

四、Spring IOC容器的启动

结合上面介绍的web容器的启动过程,以及接口ServletContextListener,ContextLoaderListener,我们来看看Spring IOC容器是怎样启动的。

我们知道在web.xml中都会有这个ContextLoaderListener监听器的配置,我们从上面的ContextLoaderListener接口的定义中可以看到,ContextLoaderListener它实现了ServletContextListener,这个接口里面的方法会结合web容器的生命周期被调用。因为ServletContextListener是ServletContext的监听者,如果ServletContext发生变化,会触发相应的事件,而监听者一直对这些事件进行监听,如果接受到了监听的事件,就会作于相应处理。例如在服务器启动,ServletContext被创建的时候,ContextLoaderListener的contextInitialized()方法被调用,这个方法就是spring容器启动的入口点。

我们从代码的角度,具体来看看:

/**
* Initialize the root web application context.
*/
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
} /**
* Close the root web application context.
*/
@Override
public void contextDestroyed(ServletContextEvent event) {
closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}

由于在ContextLoaderListener中关联了contextLoader对象,ContextLoader顾名思义就是context的加载器,由它来完成context的加载:

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
} Log logger = LogFactory.getLog(ContextLoader.class);
servletContext.log("Initializing Spring root WebApplicationContext");
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis(); try {
// Store context in local instance variable, to guarantee that
// it is available on ServletContext shutdown.
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
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 ->
// determine parent for root web application context, if any.
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
} if (logger.isDebugEnabled()) {
logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
} return this.context;
}
catch (RuntimeException ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
catch (Error err) {
logger.error("Context initialization failed", err);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
throw err;
}
}

初始化web的context做了两件事情:

1.查看是否指定了父容器,如果存在父容器则获取父容器;

2.创建webApplicationContext,配置并且刷新实例化整个SpringApplicationContext中的Bean,并指定父容器。

因此,如果我们的Bean配置出错的话,在容器启动的时候,会抛异常出来的。

下面看看是怎样创建webApplicationContext的

protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
//取得配置的Web应用程序上下文类,如果没有配置,则使用缺省的类XmlWebApplicationContext
Class<?> contextClass = determineContextClass(sc);
//如果contextClass不是可配置的Web应用程序上下文的子类,则抛出异常,停止初始化
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
//实例化需要产生的IOC容器 也就是实例化XmlWebApplicationContext
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}

实例化好XmlWebApplicationContext后,我们再来看看是如何配置ApplicationContext,并实例化bean的

    protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
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
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
} wac.setServletContext(sc);
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
} // 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(sc, null);
} customizeContext(sc, wac);
wac.refresh();
}

这个refresh方法是我们后面讲IOC容器的重点,这里IOC容器启动也就到这里了。后面是真正的IOC怎么加载Resource、解析BeanDefinition、注册、依赖注入。

Spring IOC容器在Web容器中是怎样启动的的更多相关文章

  1. spring源码研究之IoC容器在web容器中初始化过程

    转载自 http://ljbal.iteye.com/blog/497314 前段时间在公司做了一个项目,项目用了spring框架实现,WEB容器是Tomct 5,虽然说把项目做完了,但是一直对spr ...

  2. IOC容器在web容器中初始化——(一)两种配置方式

    参考文章http://blog.csdn.net/liuganggao/article/details/44083817,http://blog.csdn.net/u013185616/article ...

  3. Spring IOC(二)容器初始化

    本系列目录: Spring IOC(一)概览 Spring IOC(二)容器初始化 Spring IOC(三)依赖注入 Spring IOC(四)总结 目录 一.ApplicationContext接 ...

  4. 基于纯Java代码的Spring容器和Web容器零配置的思考和实现(3) - 使用配置

    经过<基于纯Java代码的Spring容器和Web容器零配置的思考和实现(1) - 数据源与事务管理>和<基于纯Java代码的Spring容器和Web容器零配置的思考和实现(2) - ...

  5. Spring源码解析-Web容器启动过程

    Web容器启动过程,主要讲解Servlet和Spring容器结合的内容. 流程图如下: Web容器启动的Root Context是有ContextLoaderListener,一般使用spring,都 ...

  6. spring boot 加载web容器tomcat流程源码分析

    spring boot 加载web容器tomcat流程源码分析 我本地的springboot版本是2.5.1,后面的分析都是基于这个版本 <parent> <groupId>o ...

  7. spring 和springmvc 在 web.xml中的配置

    (1)问题:如何在Web项目中配置Spring的IoC容器? 答:如果需要在Web项目中使用Spring的IoC容器,可以在Web项目配置文件web.xml中做出如下配置: <!-- Sprin ...

  8. IOC容器在web容器中初始化过程——(二)深入理解Listener方式装载IOC容器方式

    先来看一下ContextServletListener的代码 public class ContextLoaderListener extends ContextLoader implements S ...

  9. spring源码:web容器启动(li)

    web项目中可以集成spring的ApplicationContext进行bean的管理,这样使用起来bean更加便捷,能够利用到很多spring的特性.我们比较常用的web容器有jetty,tomc ...

随机推荐

  1. 3d旋转动画焦点图

    在线演示 本地下载

  2. pxe-kickstart批量部署文档

    #PXE安装: yum install syslinux xinetd tftp-server httpd -y yum install dhcp -y yum install system-conf ...

  3. jQuery对象和dom对象的转换

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  4. Bootstrap——优秀的开源前端框架

    Bootstrap是著名的社交网站.微博的先驱Twitter在2011年8月推出的开源WEB前端框架,集合CSS和HTML,使用了最新的浏览器技术,为快速WEB开发提供了一套前端工具包,包括布局.网格 ...

  5. NumPy在数组上的迭代

    NumPy - 数组上的迭代 NumPy 包包含一个迭代器对象numpy.nditer. 它是一个有效的多维迭代器对象,可以用于在数组上进行迭代. 数组的每个元素可使用 Python 的标准Itera ...

  6. PHP服务器变量$_SERVER

    常用的就几个,自己print_r($_SERVER); 看看. $_SERVER['PHP_SELF'] #当前正在执行脚本的文件名,与 document root相关. $_SERVER['argv ...

  7. Button实现图文混排

    Button实现图文混排 一.简介 本文介绍两种图文混排方式 1.android:drawableTop="@drawable/star"实现文字上有图片 当然有上下左右等等 2. ...

  8. 在Windows下MyEclipse运行JAVA程序连接HBASE读取数据出错

    运行环境:Hadoop-2.5.0+Hbase-0.98.6 问题描述: 15/06/11 15:35:50 ERROR Shell: Failed to locate the winutils bi ...

  9. spring boot配置德鲁伊

    1.引入相关依赖,全部依赖是上一篇spring boot+mybatis依赖的基础上,再加上下边的依赖,如下: <!-- Druid数据库连接池组件 --> <dependency& ...

  10. CC攻击工具list

    从论文里抠出来的工具列表如下,后面有黑产的工具以及网络上摘录的工具: 分类:(1)有僵尸网络(是否代理服务器)&没有的==>(2)单一url&混合url(多线程,压测为主,dem ...