【图解Springboot】WebMvc自动装配

1,427 阅读2分钟

关于源码解析的文章,我感觉阅读学习的效率并不高。没有脑图来的实在,自顶向下自行学习,能大大增加学习效率。【图解Springboot】系列文章只放干货,不说废话。图片仅供收藏,转载请标明出处,谢谢各位小伙伴!

思维导图

总结

  • WebMvcAutoConfiguration是Springboot的自动装载WebMvc的入口,这一点可以通过spring.factories配置文件得知。
  • WebMvcAutoConfiguration在加载前,@AutoConfigureAfter会先加载DispatcherServletAutoConfiguration,而DispatcherServletAutoConfiguration加载前又会加载ServletWebServerFactoryAutoConfiguration

  • WebMvcAutoConfiguration会加载EnableWebMvcConfigurationWebMvcAutoConfigurationAdapter 两个内部类创建并配置包括消息转换器视图解析器处理器映射器处理器适配器静态资源映射配置等。
  • SpringBoot会根据当前classpath下的类来决定装配哪些组件,启动哪种类型的Web容器`
  • 配置 SpringBoot 应用除了可以使用 properties、yml文件之外,还可以使用 Customizer 来自定义编程式配置。

[附] SpringMvc执行流程

1.DispatcherServlet表示前置控制器,是整个SpringMVC的控制中心。用户发出请求,DispatcherServlet接收请求并拦截请求。

2.HandlerMapping为处理器映射。DispatcherServlet调用HandlerMapping,HandlerMapping根据请求url查找Handler

3.HandlerExecution表示具体的Handler,其主要作用是根据url查找控制器,如上url被查找控制器为:input-product

4.HandlerExecution将解析后的信息传递给DispatcherServlet,如解析控制器映射等

5.HandlerAdapter表示处理器适配器,其按照特定的规则去执行Handler

6.Handler让具体的Controller执行

7.Controller将具体的执行信息返回给HandlerAdapter,如ModelAndView

8.HandlerAdapter将视图逻辑名或模型传递给DispatcherServlet

9.DispatcherServlet调用视图解析器(ViewResolver)来解析HandlerAdapter传递的逻辑视图名

10.视图解析器将解析的逻辑视图名传给DispatcherServlet

11.DispatcherServlet根据视图解析器解析的视图结果,调用具体的视图

12.最终视图呈现给用户。

当然日常开发中,我们并不一定会用到ViewResolver,大多数情况是返回JSON数据。@RestController中的@ResponseBody会帮我们处理这个问题。

/**
 * Annotation that indicates a method return value should be bound to the web
 * response body. Supported for annotated handler methods.
 *
 * <p>As of version 4.0 this annotation can also be added on the type level in
 * which case it is inherited and does not need to be added on the method level.
 *
 * @author Arjen Poutsma
 * @since 3.0
 * @see RequestBody
 * @see RestController
 */