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

时间:2022-12-30 20:06:54

先来看一下ContextServletListener的代码

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
public ContextLoaderListener() {
}
public ContextLoaderListener(WebApplicationContext context) {
super(context);
}
/**
  这个方法就是用来初始化web application context的
  服务器启动时,检测到此监听类,系统会调用此方法。
*/
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
/**
  服务器关闭时,这个方法调用,用来销毁容器
*/
  @Override
  public void contextDestroyed(ServletContextEvent event) {
    closeWebApplicationContext(event.getServletContext());
    ContextCleanupListener.cleanupAttributes(event.getServletContext());
  }
}
 
初始化方法contextInitialized里调用了父类ContextLoader的initWebApplicationContext方法
下面我们看下initWebApplicationContext方法的代码
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
/**
webApplicationContext只能存在一个,若重复会抛出IllegalStateException异常
从servletContext中获取ApplicationContext容器;如果已经存在,则提示初始化容器失败,检查web.xml文件中是否定义有多个容器加载器
ServletContext接口的简述:public interface ServletContext
定义了一系列方法用于与相应的servlet容器通信,比如:获得文件的MIME类型,分派请求,或者是向日志文件写日志等。
每一个web-app只能有一个ServletContext,web-app可以是一个放置有web application 文件的文件夹,也可以是一个.war的文件。
ServletContext对象包含在ServletConfig对象之中,ServletConfig对象在servlet初始化时提供servlet对象。
*/
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) {
//若WebApplicationContext容器为空,则创建一个WebApplicationContext容器
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);
}
//配置完成后,进行配置和刷新WebApplicationContext
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
//把容器放入到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;
}
}
从上面的代码可以看出,我们创建好的applicationContext容器会放在servletContext中。servletContext是什么  呢?  
  
在web容器中,通过ServletContext为Spring的IOC容器提供宿主环境,对应的建立起一个IOC容器的体系。其中,首先需要建立的是根上下文,这个上下文持有的对象可以有业务对象,数据存取对象,资源,事物管理器等各种中间层对象。在这个上下文的基础上,和web MVC相关还会有一个上下文来保存控制器之类的MVC对象,这样就构成了一个层次化的上下文结构。
 
 
真正创建ApplicationContext的方法是在createWebApplicationContext方法中完成的。
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
// 首先决定要创建的applicationContext容器的类
Class<?> contextClass = determineContextClass(sc);
// 如果获取到的类不是ConfigurableWebApplicationContext类型的,则创建容器失败,所以这里创建的容器必须是ConfigurableWebApplicationContext类型的 if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
//通过BeanUtils的instantiateClass方法创建
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
determineContextClass()方法获取了要创建的容器类
 protected Class determineContextClass(ServletContext servletContext) throws ApplicationContextException
{
// 从web.xml中获取需要初始化的容器的类名
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
// 如果获取到的类名不为空,则创建该容器的Class对象
if (contextClassName != null)
{
try {
return ClassUtils.forName(contextClassName);
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load custom context class [" + contextClassName + "]", ex);
}
}
// 否则创建默认的容器的Class对象,即:org.springframework.web.context.support.XmlWebApplicationContext
// 在创建ContextLoader时,defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);这句代码已经准备好默认的容器类
else
{
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
try
{
return ClassUtils.forName(contextClassName);
}
catch (ClassNotFoundException ex)
{
throw new ApplicationContextException(
"Failed to load default context class [" + contextClassName + "]", ex);
}
}
}
    该方法首先判断从web.xml文件的初始化参数CONTEXT_CLASS_PARAM(的定义为public static final String CONTEXT_CLASS_PARAM = "contextClass";)获取的的类名是否存在,如果存在,则容器的Class;否则返回默认的Class。如何获取默认的容器Class,注意看创建contextLoader时的代码注释就知道了。
    由此看来,spring不仅有默认的applicationContext的容器类,还允许我们自定义applicationContext容器类,不过Spring不建义我们自定义applicationContext容器类。
    
   在通过createWebApplicationContext()方法创建WebApplicationContext容器之后,会调用configureAndRefreshWebApplicationContext()方法为容器初始化配置文件中定义的bean类,它的实现过程还没搞清楚,下一章节再来做解释(=_=)。
 
   最后放上前辈的两张图,帮助大家更容易理解此配置的实现原理。
IOC容器在web容器中初始化过程——(二)深入理解Listener方式装载IOC容器方式
IOC容器在web容器中初始化过程——(二)深入理解Listener方式装载IOC容器方式
 

IOC容器在web容器中初始化过程——(二)深入理解Listener方式装载IOC容器方式的更多相关文章

  1. ASP&period;NET Web API 控制器创建过程&lpar;二&rpar;

    ASP.NET Web API 控制器创建过程(二) 前言 本来这篇随笔应该是在上周就该写出来发布的,由于身体跟不上节奏感冒发烧有心无力,这种天气感冒发烧生不如死,也真正的体会到了什么叫病来如山倒,病 ...

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

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

  3. ABP中模块初始化过程&lpar;二&rpar;

    在上一篇介绍在StartUp类中的ConfigureService()中的AddAbp方法后我们再来重点说一说在Configure()方法中的UserAbp()方法,还是和前面的一样我们来通过代码来进 ...

  4. web&period;xml文件初始化过程

    在使用各种框架后,有时会发现不了了错误处在哪里,了解Servlet的初始化过程(也可以说是web.xml的初始化吧),也许对你对于框架的理解与报错的原因理解会有帮助 context-param &gt ...

  5. 对web应用中单一入口模式的理解及php实现

    在我们web应用的开发中,经常会听见或看见单一入口模式,在我开始学习tp框架的时候也不理解为什么要运用一个单一入口模式,只是会使用,最近自己在搞一个小东西的时候才明白为什么在web开发中要运用单一入口 ...

  6. 如何把web&period;xml中的context-param、Servlet、Listener和Filter定义添加到SpringBoot中

    把传统的web项目迁移到SpringBoot中,少不了web.xml中的context-param.Servlet.Filter和Listener等定义的迁移. 对于Servlet.Filter和Li ...

  7. 关于bottle WEB框架中签名cookie的一点理解

    首先要理解一个概念 MAC (message authenticate code) 消息认证码(带密钥的Hash函数):密码学中,通信实体双方使用的一种验证机制,保证消息数据完整性的一种工具. 构造方 ...

  8. SpringBoot启动流程分析(四):IoC容器的初始化过程

    SpringBoot系列文章简介 SpringBoot源码阅读辅助篇: Spring IoC容器与应用上下文的设计与实现 SpringBoot启动流程源码分析: SpringBoot启动流程分析(一) ...

  9. Java 容器在实际项目中的应用

    前言:在java开发中我们离不开集合数组等,在java中有个专有名词:"容器" ,下面会结合Thinking in Java的知识和实际开发中业务场景讲述一下容器在Web项目中的用 ...

随机推荐

  1. JAVAWEB学习

    http://www.cnblogs.com/xdp-gacl/p/3744053.html JavaWeb学习总结(三)——Tomcat服务器学习和使用(二)

  2. UVALive 4223 Trucking 二分&plus;spfa

    Trucking 题目连接: https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8& ...

  3. OC面向对象的三大特征

    OC面向对象的三大特征 1.OC面向对象的三大特封装 1)封装:完整的说是成员变量的封装. 2)在成语方法里面的成员变量最好不要使用@public这样会直接暴露在外面被别人随随便便修改,封装的方法还可 ...

  4. 【NOIP2016】【LCA】【树上差分】【史诗级难度】天天爱跑步

    学弟不是说要出丧题吗>>所以我就研究了1天lca又研究了1天tj然后研究了一天天天爱跑步,终于写了出来.(最后的平均用时为240ms...比学弟快了1倍...) 题意:给你颗树,然后有m个 ...

  5. 统计Java项目的代码行数

    Java项目谈论行数多少有点无聊,但是有的时候就想看看一个开源的代码的量级,用Shell命令统计再合适不过了 去掉空行和注释: find . -name "*.java" |xar ...

  6. &lbrack;转&rsqb;VS2012正则查找

    本文转自:http://blog.csdn.net/u013688451/article/details/52840325 工作中有时需要用到 正则查找,例如 想找 所有用到 某个数据库表的地方 st ...

  7. ASP&period;NET MVC 跨controller函数调用

    var controller = DependencyResolver.Current.GetService<ControllerClassName>(); controller.User ...

  8. UVA 147(子集和问题)

     Dollars New Zealand currency consists of $100, $50, $20, $10, and $5 notes and $2, $1, 50c, 20c, 10 ...

  9. maven 使用错误

    使用mvn test mvn test -Dtest=测试包名.测试类名时 [ERROR] Failed to execute goal org.apache.maven.plugins:maven- ...

  10. php 备份数据库代码&lpar;生成word&comma;excel&comma;json&comma;xml&comma;sql&rpar;

    单表备份代码: 复制代码代码如下: <?php class Db { var $conn; function Db($host="localhost",$user=&quot ...