原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9502069.html
一、概述
我说的容器启动流程涉及两种情况,SSM开发模式和Springboot开发模式。
SSM开发模式中,需要配置web.xml文件用作启动配置文件,而Springboot开发模式中由main方法直接启动。
下面是web项目中容器启动的流程,起点是web.xml中配置的ContextLoaderListener监听器。
二、流程解析
Tomcat服务器启动时会读取项目中web.xml中的配置项来生成ServletContext,在其中注册的ContextLoaderListener是ServletContextListener接口的实现类,ServletContext创建的时候会触发其contextInitialized()初始化方法的执行。而Spring容器的初始化操作就在这个方法之中被触发。
来自:ContextLoaderListener
1 /** 2 * Initialize the root web application context. 3 */ 4 @Override 5 public void contextInitialized(ServletContextEvent event) { 6 initWebApplicationContext(event.getServletContext()); 7 }
上面方法中contextInitialized其实是实现接口中的方法。其中调用了initWebApplicationContext方法进行Springweb容器的创建。
来自:ContextLoader
1 public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { 2 //SpringIOC容器的重复性创建校验 3 if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { 4 throw new IllegalStateException( 5 "Cannot initialize context because there is already a root application context present - " + 6 "check whether you have multiple ContextLoader* definitions in your web.xml!"); 7 } 8 9 Log logger = LogFactory.getLog(ContextLoader.class); 10 servletContext.log("Initializing Spring root WebApplicationContext"); 11 if (logger.isInfoEnabled()) { 12 logger.info("Root WebApplicationContext: initialization started"); 13 } 14 //记录Spring容器创建开始时间 15 long startTime = System.currentTimeMillis(); 16 17 try { 18 // Store context in local instance variable, to guarantee that 19 // it is available on ServletContext shutdown. 20 if (this.context == null) { 21 //创建Spring容器实例 22 this.context = createWebApplicationContext(servletContext); 23 } 24 if (this.context instanceof ConfigurableWebApplicationContext) { 25 ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; 26 if (!cwac.isActive()) { 27 //容器只有被刷新至少一次之后才是处于active(激活)状态 28 if (cwac.getParent() == null) { 29 //此处是一个空方法,返回null,也就是不设置父级容器 30 ApplicationContext parent = loadParentContext(servletContext); 31 cwac.setParent(parent); 32 } 33 //重点操作:配置并刷新容器 34 configureAndRefreshWebApplicationContext(cwac, servletContext); 35 } 36 } 37 //将创建完整的Spring容器作为一条属性添加到Servlet容器中 38 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); 39 40 ClassLoader ccl = Thread.currentThread().getContextClassLoader(); 41 if (ccl == ContextLoader.class.getClassLoader()) { 42 //如果当前线程的类加载器是ContextLoader类的类加载器的话,也就是说如果是当前线程加载了ContextLoader类的话,则将Spring容器在ContextLoader实例中保留一份引用 43 currentContext = this.context; 44 } 45 else if (ccl != null) { 46 //添加一条ClassLoader到Springweb容器的映射 47 currentContextPerThread.put(ccl, this.context); 48 } 49 50 if (logger.isDebugEnabled()) { 51 logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + 52 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); 53 } 54 if (logger.isInfoEnabled()) { 55 long elapsedTime = System.currentTimeMillis() - startTime; 56 logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); 57 } 58 59 return this.context; 60 } 61 catch (RuntimeException ex) { 62 logger.error("Context initialization failed", ex); 63 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); 64 throw ex; 65 } 66 catch (Error err) { 67 logger.error("Context initialization failed", err); 68 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); 69 throw err; 70 } 71 }
源码中WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE的值为:WebApplicationContext.class.getName() + ".ROOT",这个是Spring容器在Servlet容器中的属性名。
在这段源码中主要是概述Spring容器的创建和初始化,分别由两个方法实现:createWebApplicationContext方法和configureAndRefreshWebApplicationContext方法。
首先,我们需要创建Spring容器,我们需要决定使用那个容器实现。
1 protected WebApplicationContext createWebApplicationContext(ServletContext sc) { 2 //决定使用哪个容器实现 3 Class<?> contextClass = determineContextClass(sc); 4 if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) { 5 throw new ApplicationContextException("Custom context class [" + contextClass.getName() + 6 "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]"); 7 } 8 //反射方式创建容器实例 9 return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); 10 }
1 //我们在web.xml中以 <context-param> 的形式设置contextclass参数来指定使用哪个容器实现类, 2 //若未指定则使用默认的XmlWebApplicationContext,其实这个默认的容器实现也是预先配置在一个 3 //叫ContextLoader.properties文件中的 4 protected Class<?> determineContextClass(ServletContext servletContext) { 5 //获取Servlet容器中配置的系统参数contextClass的值,如果未设置则为null 6 String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM); 7 if (contextClassName != null) { 8 try { 9 return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader()); 10 } 11 catch (ClassNotFoundException ex) { 12 throw new ApplicationContextException( 13 "Failed to load custom context class [" + contextClassName + "]", ex); 14 } 15 } 16 else { 17 //获取预先配置的容器实现类 18 contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName()); 19 try { 20 return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader()); 21 } 22 catch (ClassNotFoundException ex) { 23 throw new ApplicationContextException( 24 "Failed to load default context class [" + contextClassName + "]", ex); 25 } 26 } 27 }
BeanUtils是Spring封装的反射实现,instantiateClass方法用于实例化指定类。
这么看来,一般基于Spring的web服务使用的都是XmlWebApplicationContext作为容器实现类的。
到此位置容器实例就创建好了,下一步就是配置和刷新了。
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 wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + 12 ObjectUtils.getDisplayString(sc.getContextPath())); 13 } 14 } 15 //在当前Spring容器中保留对Servlet容器的引用 16 wac.setServletContext(sc); 17 //设置web.xml中配合的contextConfigLocation参数值到当前容器中 18 String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM); 19 if (configLocationParam != null) { 20 wac.setConfigLocation(configLocationParam); 21 } 22 23 // The wac environment's #initPropertySources will be called in any case when the context 24 // is refreshed; do it eagerly here to ensure servlet property sources are in place for 25 // use in any post-processing or initialization that occurs below prior to #refresh 26 //在容器刷新之前,提前进行属性资源的初始化,以备使用,将ServletContext设置为servletContextInitParams 27 ConfigurableEnvironment env = wac.getEnvironment(); 28 if (env instanceof ConfigurableWebEnvironment) { 29 ((ConfigurableWebEnvironment) env).initPropertySources(sc, null); 30 } 31 //取得web.xml中配置的contextInitializerClasses和globalInitializerClasses对应的初始化器,并执行初始化操作,需自定义初始化器 32 customizeContext(sc, wac); 33 //刷新容器 34 wac.refresh(); 35 }
上面源码中customizeContext方法的目的是在刷新容器之前对容器进行自定义的初始化操作,需要我们实现ApplicationContextInitializer<C extends ConfigurableApplicationContext>接口,然后将其配置到web.xml中即可生效。
1 protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) { 2 //获取初始化器类集合 3 List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses = 4 determineContextInitializerClasses(sc); 5 6 for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) { 7 Class<?> initializerContextClass = 8 GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class); 9 if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) { 10 throw new ApplicationContextException(String.format( 11 "Could not apply context initializer [%s] since its generic parameter [%s] " + 12 "is not assignable from the type of application context used by this " + 13 "context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(), 14 wac.getClass().getName())); 15 } 16 //实例化初始化器并添加到集合中 17 this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass)); 18 } 19 //排序并执行,编号越小越早执行 20 AnnotationAwareOrderComparator.sort(this.contextInitializers); 21 for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) { 22 initializer.initialize(wac); 23 } 24 }
1 protected List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> 2 determineContextInitializerClasses(ServletContext servletContext) { 3 4 List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> classes = 5 new ArrayList<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>>(); 6 //通过<context-param>属性配置globalInitializerClasses获取全局初始化类名 7 String globalClassNames = servletContext.getInitParameter(GLOBAL_INITIALIZER_CLASSES_PARAM); 8 if (globalClassNames != null) { 9 for (String className : StringUtils.tokenizeToStringArray(globalClassNames, INIT_PARAM_DELIMITERS)) { 10 classes.add(loadInitializerClass(className)); 11 } 12 } 13 //通过<context-param>属性配置contextInitializerClasses获取容器初始化类名 14 String localClassNames = servletContext.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM); 15 if (localClassNames != null) { 16 for (String className : StringUtils.tokenizeToStringArray(localClassNames, INIT_PARAM_DELIMITERS)) { 17 classes.add(loadInitializerClass(className)); 18 } 19 } 20 21 return classes; 22 }
initPropertySources操作用于配置属性资源,其实在refresh操作中也会执行该操作,这里提前执行,目的为何,暂未可知。
到达refresh操作我们先暂停。refresh操作是容器初始化的操作。是通用操作,而到达该点的方式确实有多种,每种就是一种Spring的开发方式。
除了此处的web开发方式,还有Springboot开发方式,貌似就两种。。。下面说说Springboot启动的流程,最后统一说refresh流程。