官方文档描述(springboot2.4version),主要参考springboot文档写下这个文章
springboot:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-spring-mvc
spring-webmvc:https://docs.spring.io/spring-framework/docs/5.3.4/reference/html/web.html#mvc
通过官网文档学习springmvc
springboot如何自动配置springmvc
springboot自动帮我们配置好的
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
The auto-configuration adds the following features on top of Spring’s defaults:
- Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
beans. - Support for serving static resources, including support for WebJars
- Automatic registration of
Converter
,GenericConverter
, andFormatter
beans. - Support for
HttpMessageConverters
- Automatic registration of
MessageCodesResolver
- Static
index.html
support. Automatic use of a
ConfigurableWebBindingInitializer
bean三种修改配置文件的方法(1普通,2定制化,3全部重置)太干了
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own
@Configuration
class of typeWebMvcConfigurer
but without@EnableWebMvc
.- If you want to provide custom instances of
RequestMappingHandlerMapping
,RequestMappingHandlerAdapter
, orExceptionHandlerExceptionResolver
, and still keep the Spring Boot MVC customizations, you can declare a bean of typeWebMvcRegistrations
and use it to provide custom instances of those components. If you want to take complete control of Spring MVC, you can add your own
@Configuration
annotated with@EnableWebMvc
, or alternatively add your own@Configuration
-annotatedDelegatingWebMvcConfiguration
as described in the Javadoc of@EnableWebMvc
.自动配置的源码
自动配置类:org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
源码自己可以去看
简单分析一下作用:@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration
这是类上的注解,说明了生效和不生效的条件,以及生效的一个顺序,具体的配置要看里面嵌套的配置类和注册Bean
主要功能点的逻辑在内部的2个静态配置类public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer
- 功能点就是springboot帮我们写的逻辑都在这个类
- 我们自己额外添加的功能也仿照这个类去写,这是官方的建议
- public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware
- 其中DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport,官方建议如果要完全接管springmvc,就使用@EnableWebMvc或者继承DelegatingWebMvcConfiguration然后自己实现 ,最原始的就继承WebMvcConfigurationSupport,然后自己重写大部分的功能
- WebMvcConfigurationSupport相当于是一个原始的配置类,只有基本的实现,子类DelegatingWebMvcConfiguration 实现少许功能,EnableWebMvcConfiguration 实现大部分功能