官方文档:https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration


ContentNegotiatingViewResolver 内容协商视图解析器

我们可以自己给容器中去添加一个视图解析器;这个类就会帮我们自动的将它组合进来
这个视图解析器就是用来组合所有的视图解析器的

  1. public class MyMvcConfig implements WebMvcConfigurer {
  2. //ViewResolver 实现了视图解析器接口的类,我们就可以把它看作视图解析器
  3. @Bean
  4. public ViewResolver myViewResolver(){
  5. return new MyViewResolver();
  6. }
  7. // 自定义了一个自己的属兔解析器MyViewResolver
  8. public static class MyViewResolver implements ViewResolver{
  9. @Override
  10. public View resolveViewName(String s, Locale locale) throws Exception {
  11. return null;
  12. }
  13. }

我们给 DispatcherServlet 中的 doDispatch方法 加个断点进行调试一下,发现:
image.png
我们自己定义的视图解析器就在这里!!
结论:我们如果想要使用自己定制化的东西,我们只需要给容器中添加这个组件就好了!

修改spriungboot的默认配置

image.png
如果有些组件可以存在多个,比如我们的视图解析器,就将用户配置的和自己默认的组合起来!
扩展使用SpringMVC 官方文档如下:
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.
我们要做的就是编写一个@Configuration注解类,并且类型要为WebMvcConfigurer,还不能标注@EnableWebMvc注解

  1. //如果,你想diy一些定制化的功能,只要写这个组件,然后将他交给springboot,springboot就会帮我们自动装配
  2. //扩展springmvc dispatchservlet
  3. @Configuration
  4. //@EnableWebMvc 这玩意就是导入了一个类:DelegatingWebMvcConfiguration:从容器中获取所有的webmvcconfig
  5. public class MyMvcConfig implements WebMvcConfigurer {
  6. @Override
  7. public void addViewControllers(ViewControllerRegistry registry) {
  8. registry.addViewController("/pp").setViewName("test");
  9. }
  10. }

为什么不能有这个注解呢?
我们点进DelegatingWebMvcConfiguration源码

  1. public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
  2. private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
  3. // 从容器中获取所有的webmvcConfigurer
  4. @Autowired(required = false)
  5. public void setConfigurers(List<WebMvcConfigurer> configurers) {
  6. if (!CollectionUtils.isEmpty(configurers)) {
  7. this.configurers.addWebMvcConfigurers(configurers);
  8. }
  9. }
  10. }

而在WebMvcAutoConfiguration中有这些条件
image.png
所以,一旦映入了 WebMvcConfigurationSupport .class自动装配全面失效!!
所有的WebMvcConfiguration都会被作用,不止Spring自己的配置类,我们自己的配置类当然也会被调用;

全面接管SpringMVC

全面接管即:SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己去配置!
只需在我们的配置类中要加一个@EnableWebMvc。
@EnableWebMvc将WebMvcConfigurationSupport组件导入进来了;
而导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能!