spring容器启动原理分析1

在项目的web.xml中配置

1 <listener>
2 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
3 </listener>

此配置为spring容器加载入口,因为其javax.servlet.ServletContextListener接口。

下面代码为ServletContextListener的源码:

public interface ServletContextListener extends EventListener {
    /**
     ** Notification that the web application initialization
     ** process is starting.
     ** All ServletContextListeners are notified of context
     ** initialization before any filter or servlet in the web
     ** application is initialized.
     */
 
    public void contextInitialized ( ServletContextEvent sce );

    /**
     ** Notification that the servlet context is about to be shut down.
     ** All servlets and filters have been destroy()ed before any
     ** ServletContextListeners are notified of context
     ** destruction.
     */
    public void contextDestroyed ( ServletContextEvent sce );
}

其中contextInitialized方法为web应用加载入口,实现此方法即可在其中加载自定义初始化web应用。

回过头看ContextLoaderListener中的初始化工作:

 1 /**
 2      * Initialize the root web application context.
 3      */
 4     public void contextInitialized(ServletContextEvent event) {
 5         this.contextLoader = createContextLoader();
 6         if (this.contextLoader == null) {
 7             this.contextLoader = this;
 8         }
 9         this.contextLoader.initWebApplicationContext(event.getServletContext());
10     }

其具体初始化工作在其父类org.springframework.web.context.ContextLoader中的initWebApplicationContext方法中进行:

/**
     * Initialize Spring‘s web application context for the given servlet context,
     * using the application context provided at construction time, or creating a new one
     * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
     * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
     * @param servletContext current servlet context
     * @return the new WebApplicationContext
     * @see #ContextLoader(WebApplicationContext)
     * @see #CONTEXT_CLASS_PARAM
     * @see #CONFIG_LOCATION_PARAM
     */
    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;
        }
    }

下面我们来分析一下上面的方法中的具体工作:

1)方法determineContextClass其返回一个WebApplicationContext的实现类,要么是默认的XmlWebApplicationContext,要么是一个指定的自定义的类。

先看方法源码:

 1 /**
 2      * Return the WebApplicationContext implementation class to use, either the
 3      * default XmlWebApplicationContext or a custom context class if specified.
 4      * @param servletContext current servlet context
 5      * @return the WebApplicationContext implementation class to use
 6      * @see #CONTEXT_CLASS_PARAM
 7      * @see org.springframework.web.context.support.XmlWebApplicationContext
 8      */
 9     protected Class<?> determineContextClass(ServletContext servletContext) {
10         String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
11         if (contextClassName != null) {
12             try {
13                 return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
14             }
15             catch (ClassNotFoundException ex) {
16                 throw new ApplicationContextException(
17                         "Failed to load custom context class [" + contextClassName + "]", ex);
18             }
19         }
20         else {
21             contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
22             try {
23                 return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
24             }
25             catch (ClassNotFoundException ex) {
26                 throw new ApplicationContextException(
27                         "Failed to load default context class [" + contextClassName + "]", ex);
28             }
29         }
30     }

先查看是否有用户自定义的context类,其配置方式是在web.xml中配置初始化属性其name为contextClass,原因是:

    /**
     * Config param for the root WebApplicationContext implementation class to use: {@value}
     * @see #determineContextClass(ServletContext)
     * @see #createWebApplicationContext(ServletContext, ApplicationContext)
     */
    public static final String CONTEXT_CLASS_PARAM = "contextClass";

在web.xml中的配置例如:

<context-param>
      <param-name>contextClass</param-name>
      <param-value>xxxxxxxxxx</param-value>
  </context-param>

如果没有自定义配置的话,实现加载其默认WebApplicationContext实现类org.springframework.web.context.support.XmlWebApplicationContext。

2)方法createWebApplicationContext将determineContextClass方法返回的Class类实例化。并将其实例类向上转型为ConfigurableWebApplicationContext类型。

默认的返回应该是ConfigurableWebApplicationContext的子类org.springframework.web.context.support.XmlWebApplicationContext实例。

下面是方法的源码:

 1 /**
 2      * Instantiate the root WebApplicationContext for this loader, either the
 3      * default context class or a custom context class if specified.
 4      * <p>This implementation expects custom contexts to implement the
 5      * {@link ConfigurableWebApplicationContext} interface.
 6      * Can be overridden in subclasses.
 7      * <p>In addition, {@link #customizeContext} gets called prior to refreshing the
 8      * context, allowing subclasses to perform custom modifications to the context.
 9      * @param sc current servlet context
10      * @return the root WebApplicationContext
11      * @see ConfigurableWebApplicationContext
12      */
13     protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
14         Class<?> contextClass = determineContextClass(sc);
15         if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
16             throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
17                     "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
18         }
19         return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
20     }

3)方法configureAndRefreshWebApplicationContext配置web应用

源码为:

 1 protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
 2         if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
 3             // The application context id is still set to its original default value
 4             // -> assign a more useful id based on available information
 5             String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
 6             if (idParam != null) {
 7                 wac.setId(idParam);
 8             }
 9             else {
10                 // Generate default id...
11                 if (sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) {
12                     // Servlet <= 2.4: resort to name specified in web.xml, if any.
13                     wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
14                             ObjectUtils.getDisplayString(sc.getServletContextName()));
15                 }
16                 else {
17                     wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
18                             ObjectUtils.getDisplayString(sc.getContextPath()));
19                 }
20             }
21         }
22
23         wac.setServletContext(sc);
24         String initParameter = sc.getInitParameter(CONFIG_LOCATION_PARAM);
25         if (initParameter != null) {
26             wac.setConfigLocation(initParameter);
27         }
28         customizeContext(sc, wac);
29         wac.refresh();
30     }

其中String initParameter = sc.getInitParameter(CONFIG_LOCATION_PARAM);获取在web.xml中配置的contextConfigLocation参数来确定spring配置文件的位置。

其中的ConfigurableWebApplicationContext类型参数实际上是其子类org.springframework.web.context.support.XmlWebApplicationContext的类型参数,

其中方法customizeContext是定制化conext的方法,如果没有在web.xml中配置contextInitializerClasses初始化参数则此方法不做任何工作。

其中wac.refresh();方法其是在org.springframework.web.context.support.XmlWebApplicationContext的父类org.springframework.context.support.AbstractApplicationContext中实现。它才开始真正的spring配置工作。

时间: 2024-08-05 00:19:38

spring容器启动原理分析1的相关文章

Spring Boot启动原理解析

Spring Boot启动原理解析http://www.cnblogs.com/moonandstar08/p/6550758.html 前言 前面几章我们见识了SpringBoot为我们做的自动配置,确实方便快捷,但是对于新手来说,如果不大懂SpringBoot内部启动原理,以后难免会吃亏.所以这次博主就跟你们一起一步步揭开SpringBoot的神秘面纱,让它不在神秘. 正文 我们开发任何一个Spring Boot项目,都会用到如下的启动类 从上面代码可以看出,Annotation定义(@Sp

SpringBoot启动原理分析

用了差不多两年的SpringBoot了,可以说对SpringBoot已经很熟了,但是仔细一想SpringBoot的启动流程,还是让自己有点懵逼,不得不说是自己工作和学习的失误,所以以此文对SpringBoot的启动流程略作记录. 此文的SpringBoot启动流程分析是基于SpringBoot 1.x的,SpringBoot 2.x的启动流程与1.x的略有不同,后续再进行补充分析. 核心注解@SpringBootApplication 每个SpringBoot应用,都有一个入口类,标注@Spri

Spring容器启动后注入service到Servlet并自动执行

通常做法是定义一个Servlet,并在web.xml中配置Servlet的启动顺序<load-on-startup>的值在DispatcherServlet之后.但这样做的缺点是在Servlet中无法使用Spring的依赖注入功能,只能使用WebApplicationContext的getBean()方法获取bean. 找到的解决办法如下: 1.自定义一个用于代理启动Servlet的类DelegatingServletProxy: package cn.edu.swu.oa.common.ut

spring容器IOC原理解析

原理简单介绍: Spring容器的原理,其实就是通过解析xml文件,或取到用户配置的bean,然后通过反射将这些bean挨个放到集合中,然后对外提供一个getBean()方法,以便我们获得这些bean.下面是一段简单的模拟代码: [java] view plain copy package com.tgb.spring.factory; import java.util.HashMap; import java.util.List; import java.util.Map; import or

spring容器启动之我见

spring容器启动之我见. 本人也是自己看看源码,然后方便以后自己记忆和理解,故写此文章,如果有什么错的地方还请大家提出. 针对于tomcat做服务器的项目,我们首先看的就是web.xml文件,spring容器启动去加载监听器 看如下代码:其监听器使用spring api中的类ContextLoaderListener <context-param> <param-name>contextConfigLocation</param-name> <param-va

springboot(八) 嵌入式Servlet容器自动配置原理和容器启动原理

1.嵌入式Servlet容器自动配置原理 1.1 在spring-boot-autoconfigure-1.5.9.RELEASE.jar => springboot自动配置依赖 jar包下,EmbeddedServletContainerAutoConfiguration => 嵌入式servlet容器自动配置类 @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @Configuration @ConditionalOnWebApplicatio

spring boot应用启动原理分析

spring boot quick start 在spring boot里,很吸引人的一个特性是可以直接把应用打包成为一个jar/war,然后这个jar/war是可以直接启动的,不需要另外配置一个Web Server. 如果之前没有使用过spring boot可以通过下面的demo来感受下. 下面以这个工程为例,演示如何启动Spring boot项目: git clone [email protected]:hengyunabc/spring-boot-demo.git mvn spring-b

spring boot启动原理步骤分析

spring boot最重要的三个文件:1.启动类 2.pom.xml 3.application.yml配置文件 一.启动类->main方法 1.spring boot通过fat jar方式用jdk命令java -jar jarname.jar启动的. fat jar就是包含被引用jar包的jar,因为会包含很多jar包,所以称为fat,肥胖. 2.spring  boot通过static void main方法启动,main方法是java程序总是最先运行的地方,这个是由jvm虚拟机决定的.任

docker容器网络通信原理分析

概述 自从docker容器出现以来,容器的网络通信就一直是大家关注的焦点,也是生产环境的迫切需求.而容器的网络通信又可以分为两大方面:单主机容器上的相互通信和跨主机的容器相互通信.而本文将分别针对这两方面,对容器的通信原理进行简单的分析,帮助大家更好地使用docker. docker单主机容器通信 基于对net namespace的控制,docker可以为在容器创建隔离的网络环境,在隔离的网络环境下,容器具有完全独立的网络栈,与宿主机隔离,也可以使容器共享主机或者其他容器的网络命名空间,基本可以