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被创建的时候,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、注册、依赖注入。

转载于:https://www.cnblogs.com/whx7762/p/7762383.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值