SpringMvc中容器加载的过程源码详解

 更新时间:2023年11月08日 09:03:58   作者:你就像甜甜的益达  
这篇文章主要介绍了SpringMvc中容器加载的过程源码详解,springmvc是基于spring的一个web层框架,同样也是web层框架的有struts,struts2等等,但是struts因为漏洞等问题,被慢慢淘汰了,现在基本都在用springmvc,需要的朋友可以参考下

了解springmvc

springmvc官网

springmvc是基于spring的一个web层框架,同样也是web层框架的有struts,struts2等等,但是struts因为漏洞等问题,被慢慢淘汰了,现在基本都在用springmvc; 相信以前面试的时候总是背了springmvc的执行流程:

SpringMVC流程

1、 用户发送请求至前端控制器DispatcherServlet。

2、 DispatcherServlet收到请求调用HandlerMapping处理器映射器。

3、 处理器映射器找到具体的处理器(可以根据xml配置、注解进行查找),生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。

4、 DispatcherServlet调用HandlerAdapter处理器适配器。

5、 HandlerAdapter经过适配调用具体的处理器(Controller,后端控制器)。

6、 Controller执行完成返回ModelAndView。

7、 HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet。

8、 DispatcherServlet将ModelAndView传给ViewReslover视图解析器。

9、 ViewReslover解析后返回具体View。

10、DispatcherServlet根据View进行渲染视图(即将模型数据填充至视图中)。

11、 DispatcherServlet响应用户。

虽然背的挺熟,但是没有看过源码,印象总不是很深;因为springmvc基本都有用过,所以有些地方就简述了;

在这里插入图片描述

启动流程

首先,我们看一下在web.xml配置的一些东西:

<!-- Spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:/config/beans.xml</param-value>
	</context-param>

	<!-- Spring MVC servlet -->
	<servlet>
		<servlet-name>SpringMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<async-supported>true</async-supported>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

前面一个是配置spring容器的,后面就是配置springmvc的;DispatcherServlet顾名思义,是一个servlet,先看看DispatcherServlet的类图:

在这里插入图片描述

httpServietBean的init方法

关于servlet就不做过多描述了,servlet入口就是init方法,我们从init方法看,先执行genericServlet的init然后genericServlet又是执行子类httpServietBean的init方法:

@Override
	public final void init() throws ServletException {
		if (logger.isDebugEnabled()) {
			logger.debug("Initializing servlet '" + getServletName() + "'");
		}

		// Set bean properties from init parameters.
		// 对Servlet初始化参数封装成PropertyValues对象
		PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
		if (!pvs.isEmpty()) {
			try {
				//将serlvet封装为BeanWrapper对象
				BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
				// 资源加载器
				ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
				// 设置一个属性编辑器
				bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
				// 执行init,(留给子类覆盖的,dispatcherServlet都没有覆盖方法,所以是空的)
				initBeanWrapper(bw);
				//设置配置
				bw.setPropertyValues(pvs, true);
			}
			catch (BeansException ex) {
				if (logger.isErrorEnabled()) {
					logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
				}
				throw ex;
			}
		}

		// Let subclasses do whatever initialization they like.
		// 初始化serlvetBean了
		initServletBean();

		if (logger.isDebugEnabled()) {
			logger.debug("Servlet '" + getServletName() + "' configured successfully");
		}
	}

initServletBean方法

比较简单:

在这里插入图片描述

initWebApplicationContext方法是主要初始化子容器,跟dispatcherservlet的方法:

protected WebApplicationContext initWebApplicationContext() {
		//获取web.xml配置的spring容器
		WebApplicationContext rootContext =
				WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		WebApplicationContext wac = null;

		// web容器,一般开始为空;springboot项目则不为空;
		if (this.webApplicationContext != null) {
			// A context instance was injected at construction time -> use it
			wac = this.webApplicationContext;
			if (wac instanceof ConfigurableWebApplicationContext) {
				ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
				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 -> set
						// the root application context (if any; may be null) as the parent
						cwac.setParent(rootContext);
					}
					configureAndRefreshWebApplicationContext(cwac);
				}
			}
		}
		// 为空就查找,查找已经绑定的上下文,一般也是空
		if (wac == null) {
			// No context instance was injected at construction time -> see if one
			// has been registered in the servlet context. If one exists, it is assumed
			// that the parent context (if any) has already been set and that the
			// user has performed any initialization such as setting the context id
			wac = findWebApplicationContext();
		}
		// 根据父容器,创建web容器,就是子容器,这里面子容器进行了刷新
		if (wac == null) {
			// No context instance is defined for this servlet -> create a local one
			wac = createWebApplicationContext(rootContext);
		}

		if (!this.refreshEventReceived) {
			// Either the context is not a ConfigurableApplicationContext with refresh
			// support or the context injected at construction time had already been
			// refreshed -> trigger initial onRefresh manually here.
			// 刷新上下文,这里主要加载dispatcherservlet的组件
			onRefresh(wac);
		}

		if (this.publishContext) {
			// Publish the context as a servlet context attribute.
			// 将web容器作为servlet上下文属性进行发布
			String attrName = getServletContextAttributeName();
			getServletContext().setAttribute(attrName, wac);
			if (this.logger.isDebugEnabled()) {
				this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
						"' as ServletContext attribute with name [" + attrName + "]");
			}
		}

		return wac;
	}

createWebApplicationContext就是创建子容器的主要方法:

protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
		return createWebApplicationContext((ApplicationContext) parent);
	}
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
		// 获取web容器的类型
		Class<?> contextClass = getContextClass();
		if (this.logger.isDebugEnabled()) {
			this.logger.debug("Servlet with name '" + getServletName() +
					"' will try to create custom WebApplicationContext context of class '" +
					contextClass.getName() + "'" + ", using parent context [" + parent + "]");
		}
		if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
			throw new ApplicationContextException(
					"Fatal initialization error in servlet with name '" + getServletName() +
					"': custom WebApplicationContext class [" + contextClass.getName() +
					"] is not of type ConfigurableWebApplicationContext");
		}
		// 反射创建web容器
		ConfigurableWebApplicationContext wac =
				(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
		// 设置环境
		wac.setEnvironment(getEnvironment());
		// 设置父容器
		wac.setParent(parent);
		//设置配置文件地址
		wac.setConfigLocation(getContextConfigLocation());
		// 加载配置,刷新容器
		configureAndRefreshWebApplicationContext(wac);
		return wac;
	}

看一下加载配置和刷新容器的地方:

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
		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
			if (this.contextId != null) {
				wac.setId(this.contextId);
			}
			else {
				// Generate default id...
				wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
						ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());
			}
		}
		// 设置web容器所属的servletcontext
		wac.setServletContext(getServletContext());
		// 设置servletconfig
		wac.setServletConfig(getServletConfig());
		// 设置命名空间
		wac.setNamespace(getNamespace());
		// 设置监听器
		wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));
		// 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(getServletContext(), getServletConfig());
		}
		// web容器的钩子方法,跟spring容器的BeanPostProcess差不多
		postProcessWebApplicationContext(wac);
		// 添加一些初始化器,如果没有设置就没有
		applyInitializers(wac);
		// 刷新容器就是走的spring容器刷新
		wac.refresh();
	}

onRefresh刷新dispatcherservlet九大组件的主要地方

onRefresh在frameworkservlet方法里是空的,在dispatcherservlet里重写了onRefresh方法,我们看dispatcherservlet里面的:

@Override
	protected void onRefresh(ApplicationContext context) {
		//初始化九大组件
		initStrategies(context);
	}
protected void initStrategies(ApplicationContext context) {
		// 初始化文件上传解析器
		initMultipartResolver(context);
		// 本地化解析
		initLocaleResolver(context);
		// 主题解析器
		initThemeResolver(context);
		// 处理器映射器 保存Url映射关系
		initHandlerMappings(context);
		// 处理器适配器
		initHandlerAdapters(context);
		// 异常解析器
		initHandlerExceptionResolvers(context);
		// 视图提取器,从request中获取viemName
		initRequestToViewNameTranslator(context);
		// 视图解析器
		initViewResolvers(context);
		// 参数解析器
		initFlashMapManager(context);
	}

到此这篇关于SpringMvc中容器加载的过程源码详解的文章就介绍到这了,更多相关SpringMvc中容器加载过程内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Springboot安全框架整合SpringSecurity实现方式

    Springboot安全框架整合SpringSecurity实现方式

    这篇文章主要介绍了Spring全家桶中Springboot安全框架整合SpringSecurity的实现方式,有需要的朋友可以借鉴参考下,希望可以有所帮助
    2021-09-09
  • Java中抽象类和接口的使用及区别分析

    Java中抽象类和接口的使用及区别分析

    抽象类中可以包含普通方法和字段,这样的包含普通方法和字段可以被子类直接使用,不用重写,而接口中不能包含普通方法,子类必须重写所有的抽象方法,下面通过本文介绍Java中抽象类和接口的使用,感兴趣的朋友一起看看吧
    2025-10-10
  • springboot项目数据库配置类DatabaseConfig示例详解

    springboot项目数据库配置类DatabaseConfig示例详解

    这篇文章主要介绍了springboot项目数据库配置类DatabaseConfig实现代码,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-08-08
  • IDEA 开发多项目依赖的方法(图文)

    IDEA 开发多项目依赖的方法(图文)

    这篇文章主要介绍了IDEA 开发多项目依赖的方法(图文),本文讲一下关于使用IntelliJ IDEA基于Maven创建多模块项目的实际开发,非常具有实用价值,需要的朋友可以参考下
    2018-10-10
  • Java Scanner类用法及nextLine()产生的换行符问题实例分析

    Java Scanner类用法及nextLine()产生的换行符问题实例分析

    这篇文章主要介绍了Java Scanner类用法及nextLine()产生的换行符问题,结合实例形式分析了Scanner类功能、hasNextInt()和nextInt()方法使用及nextLine()产生的换行符问题解决方法,需要的朋友可以参考下
    2019-03-03
  • mybatis collection关联查询多个参数方式

    mybatis collection关联查询多个参数方式

    在使用MyBatis进行关联查询时,往往需要根据多个参数进行查询,例如,使用evtId和businessType作为查询条件,同时在resultMap中配置id和businessType1作为结果映射,这种情况下,可以通过<sql>标签定义参数模板,或者使用@Param注解指定参数名称
    2024-10-10
  • Java JDBC使用入门讲解

    Java JDBC使用入门讲解

    JDBC是指Java数据库连接,是一种标准Java应用编程接口( JAVA API),用来连接 Java 编程语言和广泛的数据库。从根本上来说,JDBC 是一种规范,它提供了一套完整的接口,允许便携式访问到底层数据库,本篇文章我们来了解MySQL连接JDBC的流程方法
    2022-12-12
  • Spring与Shiro整合及加载权限表达式问题

    Spring与Shiro整合及加载权限表达式问题

    这篇文章主要介绍了Spring与Shiro整合及加载权限表达式问题,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-12-12
  • Spring Boot和Kotlin的无缝整合与完美交融

    Spring Boot和Kotlin的无缝整合与完美交融

    这篇文章主要给大家介绍了关于Spring Boot和Kotlin的无缝整合与完美交融的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-06-06
  • mybatis中注解与xml配置的对应关系和对比分析

    mybatis中注解与xml配置的对应关系和对比分析

    这篇文章主要介绍了mybatis中注解与xml配置的对应关系和对比分析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08

最新评论