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 ...
随机推荐
- Apache 日志管理
日志参数 %% 百分号(Apache2.0.44或更高的版本) %a 远端IP地址 %A 本机IP地址 %B 除HTTP头以外传送的字节数 %b 以CLF格式显示的除HTTP头以外传送的字节数,也就是 ...
- ios 中实现storyboard 与xib 之间的切换
1,跳转到xib 假设有一个按钮,这个按钮就是实现跳转的,那么在这个按钮的点击事件中,代码可以这样写. AViewController *a1= [[AViewController alloc]ini ...
- C++中的内存区[译文]
C++ 中的内存区 Const Data: The const data area stores string literals and other data whose values are kno ...
- 不错的ptyhon学习网站【学习笔记】
菜鸟教程: http://www.runoob.com/python/python-tutorial.html
- sublime使用sublimelint-luacheck屏蔽指定警告
在成功安装SublimeLinter-lua与luacheck以后,如果没有语法error,则会进行警告提示. 如下图 waring: line contains trailing whitespac ...
- Maven 的41种骨架功能介绍
1: internal -> appfuse-basic-jsf (创建一个基于Hibernate,Spring和JSF的Web应用程序的原型) 2: internal -> appfu ...
- Aware接口
Aware接口: 例如: BeanNameAware接口是为了让自身Bean能够感知到,获取到自身在Spring容器中的id属性. 同理,其他的Aware接口也是为了能够感知到自身的一些属性. 比如实 ...
- SpringBoot2.0整合Sharding-Jdbc
maven: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spri ...
- 转: 在hibernate中查询使用list,map定制返回类型
在使用hibernate进行查询时,使用得最多的还是通过构建hql进行查询了.在查询的过程当中,除使用经常的查询对象方法之外,还会遇到查询一个属性,或一组聚集结果的情况.在这种情况下,我们通常就需要对 ...
- BI项目中的ETL设计详解(数据抽取、清洗与转换 )(转载)
原文:http://www.cnblogs.com/reportmis/p/5939732.html ETL是BI项目最重要的一个环节,通常情况下ETL会花掉整个项目的1/3的时间,ETL设计的好坏直 ...