Spring基础系列-容器启动流程(1)
原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9870339.html
概述
我说的容器启动流程涉及两种情况,SSM
开发模式和Springboot
开发模式。
SSM
开发模式中,需要配置web.xml
文件用作启动配置文件,而Springboot
开发模式中由main
方法直接启动。
下面是web
项目中容器启动的流程,起点是web.xml
中配置的ContextLoaderListener
监听器。
调用流程图(右键可查看大图)
流程解析
Tomcat
服务器启动时会读取项目中web.xml
中的配置项来生成ServletContext
,在其中注册的ContextLoaderListener
是ServletContextListener
接口的实现类,它会时刻监听ServletContext
的动作,包括创建和销毁,ServletContext
创建的时候会触发其contextInitialized()
初始化方法的执行。而Spring
容器的初始化操作就在这个方法之中被触发。
源码1-来自:ContextLoaderListener
/** * Initialize the root web application context. */ @Override public void contextInitialized(ServletContextEvent event) { initWebApplicationContext(event.getServletContext()); }
ContextLoaderListener
是启动和销毁Spring
的root WebApplicationContext
(根web容器
或者根web应用上下文
)的引导器,其中实现了ServletContextListener
的contextInitialized
容器初始化方法与contextDestoryed
销毁方法,用于引导根web容器
的创建和销毁。
上面方法中contextInitialized
就是初始化根web容器
的方法。其中调用了initWebApplicationContext
方法进行Spring web容器
的具体创建。
源码2-来自:ContextLoader
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { //SpringIOC容器的重复性创建校验 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"); } //记录Spring容器创建开始时间 long startTime = System.currentTimeMillis(); try { // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. if (this.context == null) { //创建Spring容器实例 this.context = createWebApplicationContext(servletContext); } if (this.context instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; if (!cwac.isActive()) { //容器只有被刷新至少一次之后才是处于active(激活)状态 if (cwac.getParent() == null) { //此处是一个空方法,返回null,也就是不设置父级容器 ApplicationContext parent = loadParentContext(servletContext); cwac.setParent(parent); } //重点操作:配置并刷新容器 configureAndRefreshWebApplicationContext(cwac, servletContext); } } //将创建完整的Spring容器作为一条属性添加到Servlet容器中 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl == ContextLoader.class.getClassLoader()) { //如果当前线程的类加载器是ContextLoader类的类加载器的话,也就是说如果是当前线程加载了ContextLoader类的话,则将Spring容器在ContextLoader实例中保留一份引用 currentContext = this.context; } else if (ccl != null) { //添加一条ClassLoader到Springweb容器的映射 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; } }
这里十分明了的显示出了ServletContext
和Spring root ApplicationContext
的关系:后者只是前者的一个属性,前者包含后者。
知识点:
ServletContext
表示的是一整个应用,其中囊括应用的所有内容,而Spring
只是应用所采用的一种框架。从ServletContext
的角度来看,Spring
其实也算是应用的一部分,属于和我们编写的代码同级的存在,只是相对于我们编码人员来说,Spring
是作为一种即存的编码架构而存在的,即我们将其看作我们编码的基础,或者看作应用的基础部件。虽然是基础部件,但也是属于应用的一部分。所以将其设置到ServletContext
中,而且是作为一个单一属性而存在,但是它的作用却是很大的。
源码中WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
的值为:WebApplicationContext.class.getName() + ".ROOT"
,这个正是Spring容器
在Servlet容器
中的属性名。
在这段源码中主要是概述Spring
容器的创建和初始化,分别由两个方法实现:createWebApplicationContext方法和configureAndRefreshWebApplicationContext方法。
首先,我们需要创建Spring容器
,我们需要决定使用哪个容器实现。
源码3-来自:ContextLoader
protected WebApplicationContext createWebApplicationContext(ServletContext sc) { //决定使用哪个容器实现 Class<?> contextClass = determineContextClass(sc); if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) { throw new ApplicationContextException("Custom context class [" + contextClass.getName() + "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]"); } //反射方式创建容器实例 return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); }
//我们在web.xml中以 <context-param> 的形式设置contextclass参数来指定使用哪个容器实现类, //若未指定则使用默认的XmlWebApplicationContext,其实这个默认的容器实现也是预先配置在一个 //叫ContextLoader.properties文件中的 protected Class<?> determineContextClass(ServletContext servletContext) { //获取Servlet容器中配置的系统参数contextClass的值,如果未设置则为null String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM); if (contextClassName != null) { try { return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader()); } catch (ClassNotFoundException ex) { throw new ApplicationContextException( "Failed to load custom context class [" + contextClassName + "]", ex); } } else { //获取预先配置的容器实现类 contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName()); try { return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader()); } catch (ClassNotFoundException ex) { throw new ApplicationContextException( "Failed to load default context class [" + contextClassName + "]", ex); } } }
BeanUtils
是Spring
封装的反射实现,instantiateClass
方法用于实例化指定类。
我们可以在web.xml
中以<context-param>
的形式设置contextclass
参数手动决定应用使用哪种Spring容器
,但是一般情况下我们都遵循Spring
的默认约定,使用ContextLoader.properties
中配置的org.springframework.web.context.WebApplicationContext
的值来作为默认的Spring容器
来创建。
源码4-来自:ContextLoader.properties
# Default WebApplicationContext implementation class for ContextLoader. # Used as fallback when no explicit context implementation has been specified as context-param. # Not meant to be customized by application developers. org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
可见,一般基于Spring
的web
应用默认使用的都是XmlWebApplicationContext
作为容器实现类的。
下面我们来看看XmlWebApplicationContext
容器实例的创建过程:
首先在XmlWebApplicationContext
中并没有自定义的构造器,反射工具调用的也是默认的无参构造器,让我们在看看其继承体系中有哪些初始化逻辑:
首先来到AbstractRefreshableWebApplicationContext
类中,其中有无参构造器逻辑:
源码5-来自:AbstractRefreshableWebApplicationContext
public AbstractRefreshableWebApplicationContext() { setDisplayName("Root WebApplicationContext"); }
可见在AbstractRefreshableWebApplicationContext中设置了容器的显示名称displayName。
然后就来到AbstractApplicationContext
类中,其中有无参与带参构造器逻辑:
源码6-来自:AbstractApplicationContext
public AbstractApplicationContext() { this(null); } public AbstractApplicationContext(ApplicationContext parent) { this.parent = parent; this.resourcePatternResolver = getResourcePatternResolver(); this.environment = this.createEnvironment(); } protected ResourcePatternResolver getResourcePatternResolver() { return new PathMatchingResourcePatternResolver(this); } protected ConfigurableEnvironment createEnvironment() { return new StandardEnvironment(); }
源码7-来自:AbstractRefreshableWebApplicationContext
@Override protected ConfigurableEnvironment createEnvironment() { return new StandardServletEnvironment(); }
可见在无参构造器中调用了带参的构造器,主要逻辑在带参构造器中,主要包括:
- 配置父级容器,此处传null,表示当前容器即为终极(root)容器;
- 配置resourcePatternResolver,资源模式解析器,其实就是针对classpath*:之类的待匹配符的资源配置的解析器,这里创建了PathMatchingResourcePatternResolver解析器实例。
- 创配置environment环境,虽然在AbstractApplicationContext中创建了StandardEnvironment实例,但是在AbstractRefreshableWebApplicationContext中重写了createEnvironment方法,所以容器持有的environment最终为StandardServletEnvironment实例。
StandardServletEnvironment实例的创建也要执行一定的初始化,这些逻辑位于AbstractEnvironment类中:
源码8-来自:AbstractEnvironment
public AbstractEnvironment() { String name = this.getClass().getSimpleName(); if (this.logger.isDebugEnabled()) { this.logger.debug(format("Initializing new %s", name)); } this.customizePropertySources(this.propertySources); if (this.logger.isDebugEnabled()) { this.logger.debug(format( "Initialized %s with PropertySources %s", name, this.propertySources)); } } protected void customizePropertySources(MutablePropertySources propertySources) { }
初始化的主要逻辑在customizePropertySources方法,当前类中的该方法是无逻辑的,会执行子类中重写的逻辑:
源码9-来自:StandardServletEnvironment
@Override protected void customizePropertySources(MutablePropertySources propertySources) { propertySources.addLast(new StubPropertySource(SERVLET_CONFIG_PROPERTY_SOURCE_NAME)); propertySources.addLast(new StubPropertySource(SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)); if (JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()) { propertySources.addLast(new JndiPropertySource(JNDI_PROPERTY_SOURCE_NAME)); } super.customizePropertySources(propertySources); }
源码10-来自:StandardEnvironment
@Override protected void customizePropertySources(MutablePropertySources propertySources) { propertySources.addLast(new MapPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties())); propertySources.addLast(new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment())); }
上面就是所有在环境初始化式执行的逻辑了,为了后面的内容阅读,有必要了解以下内容:PropertySource,PropertySources,MutablePropertySources,StubPropertySource等的作用。
PropertySource:用于封装一个键值对形式的properties属性配置文件的属性资源模型
PropertySources:继承自Iterable<PropertySource<?>>,表示的是一个或者多个PropertySource资源模型的综合模型
MutablePropertySources:实现了PropertySources接口,表示的就是多个PropertySource资源模型,其内部封装了一个链表集合propertySourceList,用于存放多个PropertySource资源模型。
private final LinkedList<PropertySource<?>> propertySourceList = new LinkedList<PropertySource<?>>(); StubPropertySource:继承自PropertySource,并不表示某一具体的资源模型,而是表示一个资源占位,当在Spring容器创建的时候,实际的资源无法被快速初始化的情况下,可以先用该类的实例进行占位,等到容器刷新的时候执行实际属性资源的替换操作。
初步了解了这四个内容之后,我们就来详细看看环境的初始化做了哪些工作?其实很简单,就是将一些配置信息添加到环境所持有的MutablePropertySources实例中的propertySourceList链表中备用,主要看看添加了那些配置信息:
-
web.xml中配置的servletContextInitParams初始化参数值
-
web.xml中配置的servletConfigInitParams初始化参数值
-
jndi配置信息jndiProperties,只有在这个JVM上有默认的JNDI环境(如Java EE环境)的情况下才会配置。
-
操作系统的属性:systemProperties
-
操作系统的环境属性:systemEnvironment
将以上内容按顺序添加到链表中备用之后,StandardServletEnvironment初始化完毕。
到此位置容器实例就创建好了,下一步就是配置和刷新了。
源码11-来自:ContextLoader
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())); } } //在当前Spring容器中保留对Servlet容器的引用 wac.setServletContext(sc); //设置web.xml中配置的contextConfigLocation参数值到当前容器中 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 //在容器刷新之前,提前进行属性资源的初始化,以备使用,将ServletContext设置为servletContextInitParams ConfigurableEnvironment env = wac.getEnvironment(); if (env instanceof ConfigurableWebEnvironment) { ((ConfigurableWebEnvironment) env).initPropertySources(sc, null); } //取得web.xml中配置的contextInitializerClasses和globalInitializerClasses对应的初始化器,并执行初始化操作,需自定义初始化器 customizeContext(sc, wac); //刷新容器 wac.refresh(); }
首先将ServletContext
的引用置入Spring容器
中,以便可以方便的访问ServletContext
;然后从ServletContext
中找到contextConfigLocation
参数的值,配置是在web.xml
中以<context-param>
形式配置的。
知识点:
在
Spring
中凡是以<context-param>
配置的内容都会在web.xml
加载的时候优先存储到ServletContext
之中,我们可以将其看成ServletContext
的配置参数,将参数配置到ServletContext
中后,我们就能方便的获取使用了,就如此处我们就能直接从ServletContext
中获取contextConfigLocation
的值,用于初始化Spring容器
。在
Java
的web
开发中,尤其是使用Spring
辅助开发的情况下,基本就是一个容器对应一套配置,这套配置就是用于初始化容器的。ServletContext
对应于<context-param>
配置,Spring容器
对应applicationContext.xml
配置,这个配置属于默认的配置,如果自定义名称就需要将其配置到<context-param>
中备用了,还有DispatchServlet
的Spring容器
对应spring-mvc.xml
配置文件。
Spring容器
的environment
表示的是容器运行的基础环境配置,其中保存的是Profile
和Properties
,其initPropertySources
方法是在ConfigurableWebEnvironment
接口中定义的,是专门用于web应用
中来执行真实属性资源与占位符资源(StubPropertySource
)的替换操作的。
源码12-来自:StandardServletEnvironment
@Override public void initPropertySources(@Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) { WebApplicationContextUtils.initServletPropertySources(getPropertySources(), servletContext, servletConfig); }
源码13-来自:WebApplicationContextUtils
public static void initServletPropertySources(MutablePropertySources sources, @Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) { Assert.notNull(sources, "'propertySources' must not be null"); String name = StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME; if (servletContext != null && sources.contains(name) && sources.get(name) instanceof StubPropertySource) { sources.replace(name, new ServletContextPropertySource(name, servletContext)); } name = StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME; if (servletConfig != null && sources.contains(name) && sources.get(name) instanceof StubPropertySource) { sources.replace(name, new ServletConfigPropertySource(name, servletConfig)); } }
从上面的源码中可以看出,这里只进行了有关Servlet的占位资源的替换操作:ServletContext和ServletConfig。
上面源码中customizeContext
方法的目的是在刷新容器之前对容器进行自定义的初始化操作,需要我们实现ApplicationContextInitializer<C extends ConfigurableApplicationContext>
接口,然后将其配置到web.xml
中即可生效。
源码14-来自:ContextLoader
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) { //获取初始化器类集合 List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses = determineContextInitializerClasses(sc); for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) { Class<?> initializerContextClass = GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class); if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) { throw new ApplicationContextException(String.format( "Could not apply context initializer [%s] since its generic parameter [%s] " + "is not assignable from the type of application context used by this " + "context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(), wac.getClass().getName())); } //实例化初始化器并添加到集合中 this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass)); } //排序并执行,编号越小越早执行 AnnotationAwareOrderComparator.sort(this.contextInitializers); for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) { initializer.initialize(wac); } }
protected List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> determineContextInitializerClasses(ServletContext servletContext) { List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> classes = new ArrayList<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>>(); //通过<context-param>属性配置globalInitializerClasses获取全局初始化类名 String globalClassNames = servletContext.getInitParameter(GLOBAL_INITIALIZER_CLASSES_PARAM); if (globalClassNames != null) { for (String className : StringUtils.tokenizeToStringArray(globalClassNames, INIT_PARAM_DELIMITERS)) { classes.add(loadInitializerClass(className)); } } //通过<context-param>属性配置contextInitializerClasses获取容器初始化类名 String localClassNames = servletContext.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM); if (localClassNames != null) { for (String className : StringUtils.tokenizeToStringArray(localClassNames, INIT_PARAM_DELIMITERS)) { classes.add(loadInitializerClass(className)); } } return classes; }
initPropertySources
操作用于配置属性资源,其实在refresh
操作中也会执行该操作,这里提前执行,目的为何,暂未可知。
到达refresh
操作我们先暂停。refresh
操作是容器初始化的操作。是通用操作,而到达该点的方式确实有多种,每种就是一种Spring
的开发方式。
除了此处的web
开发方式,还有Springboot
开发方式,貌似就两种。。。下面说说Springboot
启动的流程,最后统一说refresh
流程。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· 手把手教你更优雅的享受 DeepSeek
· AI工具推荐:领先的开源 AI 代码助手——Continue
· 探秘Transformer系列之(2)---总体架构
· V-Control:一个基于 .NET MAUI 的开箱即用的UI组件库
· 乌龟冬眠箱湿度监控系统和AI辅助建议功能的实现