Spring IOC容器在Web容器中是怎样启动的
前言
我们一般都知道怎样使用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容器中是怎样启动的的更多相关文章
- spring源码研究之IoC容器在web容器中初始化过程
转载自 http://ljbal.iteye.com/blog/497314 前段时间在公司做了一个项目,项目用了spring框架实现,WEB容器是Tomct 5,虽然说把项目做完了,但是一直对spr ...
- IOC容器在web容器中初始化——(一)两种配置方式
参考文章http://blog.csdn.net/liuganggao/article/details/44083817,http://blog.csdn.net/u013185616/article ...
- Spring IOC(二)容器初始化
本系列目录: Spring IOC(一)概览 Spring IOC(二)容器初始化 Spring IOC(三)依赖注入 Spring IOC(四)总结 目录 一.ApplicationContext接 ...
- 基于纯Java代码的Spring容器和Web容器零配置的思考和实现(3) - 使用配置
经过<基于纯Java代码的Spring容器和Web容器零配置的思考和实现(1) - 数据源与事务管理>和<基于纯Java代码的Spring容器和Web容器零配置的思考和实现(2) - ...
- Spring源码解析-Web容器启动过程
Web容器启动过程,主要讲解Servlet和Spring容器结合的内容. 流程图如下: Web容器启动的Root Context是有ContextLoaderListener,一般使用spring,都 ...
- spring boot 加载web容器tomcat流程源码分析
spring boot 加载web容器tomcat流程源码分析 我本地的springboot版本是2.5.1,后面的分析都是基于这个版本 <parent> <groupId>o ...
- spring 和springmvc 在 web.xml中的配置
(1)问题:如何在Web项目中配置Spring的IoC容器? 答:如果需要在Web项目中使用Spring的IoC容器,可以在Web项目配置文件web.xml中做出如下配置: <!-- Sprin ...
- IOC容器在web容器中初始化过程——(二)深入理解Listener方式装载IOC容器方式
先来看一下ContextServletListener的代码 public class ContextLoaderListener extends ContextLoader implements S ...
- spring源码:web容器启动(li)
web项目中可以集成spring的ApplicationContext进行bean的管理,这样使用起来bean更加便捷,能够利用到很多spring的特性.我们比较常用的web容器有jetty,tomc ...
随机推荐
- linux驱动调试--修改系统时钟终端来定位僵死问题【转】
本文转载自:http://blog.chinaunix.net/uid-20671208-id-4940381.html 原文地址:linux驱动调试--修改系统时钟终端来定位僵死问题 作者:枫露清愁 ...
- Jquery简单的选项卡实现
概述 原来对jQuery用的不是很多,主要就是表单验证这些部分,最近想要更深入的学习jQuery和JavaScript编码,就找来了一些视频进行学习,然后就做了这个简单的选项卡示例.视频学习地址见最后 ...
- JAVA基础补漏--内部类
成员内部类 public class InnerClass { public static void main(String[] args) { System.out.println("++ ...
- CNNIC成为首家UASG中国联络站
1月29日,在“2018中国域名大会暨中国互联网络信息中心(CNNIC)行业合作伙伴年会”上获悉,CNNIC日前正式完成与互联网名称与数字地址分配机构(ICANN)的签约,成为首家UASG(普遍接受指 ...
- scala学习手记30 - 闭包
首先要弄白闭包的概念. 教材中的说法是:闭包是一种特殊的函数值,闭包中封闭或绑定了在另一个作用域或上下文中定义的变量.这里说闭包是一种特殊的函数值. 维基百科中的说法是:在计算机科学中,闭包(英语:C ...
- Spring Boot的核心
1.1.1. 入口类和@SpringBootApplication Spring Boot的项目一般都会有*Application的入口类,入口类中会有main方法,这是一个标准的Java应用程序 ...
- 关于Android中根据ID名动态获取资源的两个方法
在开发中, 我们习惯了类似下面这种方式去实现引用资源: context.getResources().getDrawable(R.drawable.flower); 但是,当我们提前知道这个资源的id ...
- thinkphp3.2.3 定时任务重新加载, 无法加载新的定时任务的问题
thinkphp3.2.3 的定时任务有个坑,一旦你改名定时任何或者路径,新的定时任务将无法加载,无论你重启php还是重启nginx,甚至重启服务器,都不行. 原因是你要删掉一个类似lock文件,才可 ...
- cssrem 比例适配理解
cssrem只是帮你自动计算,省去了你在切图时,从设计稿拿到的px再根据比例转换成rem的中间过程. 这个40我无法猜测, 以前设计稿给的都是按640px(iphone5s的宽)来的,我们就按照这个比 ...
- H5滑动穿透(TODO)
https://github.com/pod4g/tool/wiki/%E7%A7%BB%E5%8A%A8%E7%AB%AF%E6%BB%9A%E5%8A%A8%E7%A9%BF%E9%80%8F%E ...