SpringBoot、Spring、SpringMVC原理梳理

本文深入探讨了Spring、SpringMVC和SpringBoot三者之间的关系及其工作原理。Spring是基础容器,管理service和dao,SpringMVC是其在Web领域的实现,负责controller。两者之间是父子容器关系。SpringBoot作为Spring的扩展,简化了项目搭建和配置。文章还详细解析了SpringMVC的DispatchServlet初始化过程和执行流程。
摘要由CSDN通过智能技术生成

SpringBoot、Spring、SpringMVC原理梳理

Spring、SpringMVC、SpringBoot三者的关系:

Spring和SpringMVC:

​ springmvc和spring都是容器,容器就是管理对象的地方,例如Tomcat,就是管理servlet对象的,而springMVC容器和spring容器,就是管理bean对象的地方,再说的直白点,springmvc就是管理controller对象的容器,spring就是管理service和dao的容器。所以在springmvc的配置文件里配置的扫描路径就是controller的路径,而spring的配置文件里自然配的就是service和dao的路径。

​ 其次, spring容器和springmvc容器的关系是父子容器的关系。spring容器是父容器,springmvc是子容器。在子容器里可以访问父容器里的对象,但是在父容器里不可以访问子容器的对象,说的通俗点就是,在controller里可以访问service对象,但是在service里不可以访问controller对象

​ 所以这么看的话,所有的bean,都是被spring或者springmvc容器管理的,他们可以直接注入。然后springMVC的拦截器也是springmvc容器管理的,所以在springmvc的拦截器里,可以直接注入bean对象。

​ web容器是管理servlet,以及监听器(Listener)和过滤器(Filter)的。这些都是在web容器的掌控范围里。但他们不在spring和springmvc的掌控范围里。因此,我们无法在这些类中直接使用Spring注解的方式来注入我们需要的对象,是无效的,web容器是无法识别的。

​ 而无法通过注解方式获取我们所需要的bean:则需要通过加载注解文件的方式。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wNwE1in6-1652669089203)(C:\Users\zhangxy\Desktop\笔记\spring\SpringBoot、Spring、SpringMVC原理梳理.assets\image-20220513220136844.png)]

​ 注意:以上代码有一个前提,那就是servlet容器在实例化ConfigListener并调用其方法之前,要确保spring容器已经初始化完毕!而spring容器的初始化也是由Listener(ContextLoaderListener)完成,因此只需在web.xml中先配置初始化spring容器的Listener,然后在配置自己的Listener。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NhetuXUu-1652669089204)(C:\Users\zhangxy\Desktop\笔记\spring\SpringBoot、Spring、SpringMVC原理梳理.assets\image-20220513220348567.png)]

​ web容器中有servlet容器,spring项目部署后存在spring容器和springmvc容器。其中spring控制service层和dao层的bean对象。springmvc容器控制controller层bean对象。servlet容器控制servlet对象。项目启动是,首先 servlet初始化,初始化过程中通过web.xml中spring的配置加载spring配置,初始化spring容器和springmvc容器。待容器加载完成。servlet初始化完成,则完成启动。
​ HTTP请求到达web容器后,会到达Servlet容器,容器通过分发器分发到具体的spring的Controller层。执行业务操作后返回结果。

​ Tomcat在启动时给每个Web应用创建一个全局的上下文环境,这个上下文就是ServletContext,其为后面的Spring容器提供宿主环境。

​ Tomcat在启动过程中触发容器初始化事件,Spring的ContextLoaderListener会监听到这个事件,它的contextInitialized方法会被调用,在这个方法中,Spring会初始化全局的Spring根容器,这个就是Spring的IoC容器,IoC容器初始化完毕后,Spring将其存储到ServletContext中,便于以后来获取。

​ Tomcat在启动过程中还会扫描Servlet,一个Web应用中的Servlet可以有多个,以SpringMVC中的DispatcherServlet为例,这个Servlet实际上是一个标准的前端控制器,用以转发、匹配、处理每个Servlet请求。

​ Servlet一般会延迟加载,当第一个请求达到时,Tomcat&Jetty发现DispatcherServlet还没有被实例化,就调用DispatcherServlet的init方法,DispatcherServlet在初始化的时候会建立自己的容器,叫做SpringMVC 容器,用来持有Spring MVC相关的Bean。

​ 同时,Spring MVC还会通过ServletContext拿到Spring根容器,并将Spring根容器设为SpringMVC容器的父容器,请注意,Spring MVC容器可以访问父容器中的Bean,但是父容器不能访问子容器的Bean, 也就是说Spring根容器不能访问SpringMVC容器里的Bean。说的通俗点就是,在Controller里可以访问Service对象,但是在Service里不可以访问Controller对象。

SpringBoot、Spring:

​ SpringBoot:Spring框架的扩展,其设计目的是简单Spring初始搭建以及开发过程,采用约定大于配置的方式,大量减少配置文件的使用,即采用默认配置即可,如有特殊需求自定义配置即可,它的一些特点如下:

​ 1.快速创建Spring应用

​ 2.内嵌Tomcat、Jetty等容器

​ 3.提供"starter" poms来简化maven依赖的配置

​ 4.消除了之前spring的xml配置

SpringBoot与Spring框架的关系:

SpringBoot框架是Spring框架的一种扩展,基于Spring技术,简化开发提供starter依赖包、内嵌容器、消除xml;

SpringBoot与SpringMVC框架的关系:

SpingMVC是web应用MVC架构的一种实现,如果一个SpringBoot项目是web项目则可以使用SpringMVC模式开发。

SpringMVC的DispatchServlet解析

DispatchServlet初始化:

​ 所在类:org.springframework.web.servlet.FrameworkServlet

​ DispatchServlet本质上是一个Servlet,所以天然遵循Servlet的生命周期。所以宏观上是Servlet生命周期调度。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mCPfRLgf-1652669089204)(C:\Users\zhangxy\Desktop\笔记\spring\SpringBoot、Spring、SpringMVC原理梳理.assets\image-20220513222309005.png)]

DispatchServlet如图中逐层继承,而GenericServlet则是实现了Servlet接口的方法。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1520f4wb-1652669089205)(C:\Users\zhangxy\Desktop\笔记\spring\SpringBoot、Spring、SpringMVC原理梳理.assets\image-20220513225452059.png)]

initServletBean

​ 作为接口的Servlet创建之后调用实现类(GenericServlet)的init方法,之后HTTPSerlvet重写init方法。在init方法中调用initServletBean方法,该方法之后再FrameworkServlet中重写。

@Override
protected final void initServletBean() throws ServletException {
   
   getServletContext().log("Initializing Spring " + getClass().getSimpleName() + " '" + getServletName() + "'");
   if (logger.isInfoEnabled()) {
   
       //输出当前Servlet名称。
      logger.info("Initializing Servlet '" + getServletName() + "'");
   }
   long startTime = System.currentTimeMillis();

   try {
   t
       //初始化WebApplicationContext
      this.webApplicationContext = initWebApplicationContext();
      initFrameworkServlet();
   }
   catch (ServletException | RuntimeException ex) {
   
      logger.error("Context initialization failed", ex);
      throw ex;
   }

   if (logger.isDebugEnabled()) {
   
      String value = this.enableLoggingRequestDetails ?
            "shown which may lead to unsafe logging of potentially sensitive data" :
            "masked to prevent unsafe logging of potentially sensitive data";
      logger.debug("enableLoggingRequestDetails='" + this.enableLoggingRequestDetails +
            "': request parameters and headers will be " + value);
   }

   if (logger.isInfoEnabled()) {
   
      logger.info("Completed initialization in " + (System.currentTimeMillis() - startTime) + " ms");
   }
}
initWebApplicationContext();

在打印完当前Servlet的名称和获取系统当前时间之后就initWebApplicationContext进行WebApplicationContext的初始化:

protected WebApplicationContext initWebApplicationContext() {
   
   WebApplicationContext rootContext =
         WebApplicationContextUtils.getWebApplicationContext(getServletContext());
   WebApplicationContext wac = null;

   
   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();
   }
   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 co
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值