狂神说Java:https://www.bilibili.com/video/BV1PE411i7CV
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 type WebMvcConfigurer but without @EnableWebMvc.
If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations 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-annotated DelegatingWebMvcConfiguration as described in the Javadoc of @EnableWebMvc.
1、结合官方文档学习源码
(1)WebMvcConfigurer是一个接口,配置类实现该接口
WebMvcAutoConfiguration类的静态内部类WebMvcAutoConfigurationAdapter
WebMvcConfigurer接口
(2)查看视图解析器类ContentNegotiatingViewResolver
发现其实现了ViewResolver接口。于是我们可以自定义视图解析器。实现了视图解析器接口的类。就可以看作视图解析器。
(3)查看视图解析器接口ViewResolver源码
需要实现这个方法。
2、自定义配置类
MyMvcConfig.java
package com.kuang.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Locale;
/**
* @Description TODO
* 扩展MVC DispatcherServlet
* 如果你想diy一些定制化的功能。只要写这个组件。然后将它交给SpringBoot,
* SpringBoot就会帮我们自动装配
* @Author Administrator
* @Date 2020/12/10 13:43
*/
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Bean
ViewResolver myViewResolver(){
return new MyViewResolver();
}
/**
* public interface ViewResolver 实现了视图解析器接口的类。就可以看作视图解析器
* 自定义视图解析器
*/
public static class MyViewResolver implements ViewResolver {
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return null;
}
}
}
3、断点调试
在SpringMVC的学习中,我们知道Spring的web框架围绕DispatcherServlet设计。DispatcherServlet的作用是将请求分发到不同的处理器。因此可以在DispatcherServlet入口处打断点,查看程序运行情况。