前言

我们一般都知道怎样使用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被创建的时候,ContextLoaderListenercontextInitialized()方法被调用,这个方法就是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. python技术

    要把zabbix弄成自动监控,下发任务,部署,事件恢复得功能

  2. linux 安装unrar

    Centos 6 32位下安装 wget http://pkgs.repoforge.org/unrar/unrar-4.2.3-1.el6.rf.i686.rpmrpm -ivh unrar-4.2 ...

  3. 解读Mirantis最新的Neutron性能测试

    最近,mirantis的工程师发布了最新的基于Mitaka版本的Neutron性能测试结果.得出的结论是:Neutron现在的性能已经可以用生产环境了. 报告的三位作者都是OpenStack社区的活跃 ...

  4. codeforces 831B. Keyboard Layouts 解题报告

    题目链接:http://codeforces.com/contest/831/problem/B 题目意思:给出两个长度为26,由小写字母组成的字符串s1和s2,对于给出的第三个字符串s3,写出对应s ...

  5. 使用SpringMVC时报错HTTP Status 405 - Request method 'GET' not supported

    GET方法不支持.我出错的原因在于,在JSP中我希望超链接a以post方式提交,但是这里写js代码时出错. <script type="text/javascript"> ...

  6. 查看SQLServer的最大连接数

    如何查看SQLServer的最大连接数?相信很多人对个很有兴趣,一下就给出两种方法: 1. 查询服务器属性 默认服务设置为0(表示不受限制). 2. SQL查看最大连接数 这里的32767就是服务器的 ...

  7. 简短的perl程序

    简短的perl程序能够实现大功能.    perl是如何做到的呢?  1. 默认变量     如果没有向函数提供参数值,则默认参数为$_:     如果没有变量用于接收一个表达式的值,则默认接收变量为 ...

  8. ASP.NET MVC 中的IResolver<T> 接口

    在ASP.NET MVC 的源码一些实体对象(比如 ControllerBuilder,ControllerFactory, Filters, ViewEngines 等)不再直接通过关键字new来创 ...

  9. S3C2440启动方式

    不管S3C2440的启动设备是什么,它都是从0x0000 0000地址开始执行程序的,所不同的是地址的映射不一样.基于S3C2440的嵌入式系统上电之后,需要首选选择启动设备,2440的启动方式选择是 ...

  10. Centos6.8 JDK配置

    记录一下在这个服务器配置的过程 ssh root@IP Password --------------------------------------------------------------- ...