ContentNegotiatingViewResolver 内容协商视图解析器
我们可以自己给容器中去添加一个视图解析器;这个类就会帮我们自动的将它组合进来
这个视图解析器就是用来组合所有的视图解析器的
public class MyMvcConfig implements WebMvcConfigurer {
//ViewResolver 实现了视图解析器接口的类,我们就可以把它看作视图解析器
@Bean
public ViewResolver myViewResolver(){
return new MyViewResolver();
}
// 自定义了一个自己的属兔解析器MyViewResolver
public static class MyViewResolver implements ViewResolver{
@Override
public View resolveViewName(String s, Locale locale) throws Exception {
return null;
}
}
我们给 DispatcherServlet 中的 doDispatch方法 加个断点进行调试一下,发现:
我们自己定义的视图解析器就在这里!!
结论:我们如果想要使用自己定制化的东西,我们只需要给容器中添加这个组件就好了!
修改spriungboot的默认配置
如果有些组件可以存在多个,比如我们的视图解析器,就将用户配置的和自己默认的组合起来!
扩展使用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注解;
//如果,你想diy一些定制化的功能,只要写这个组件,然后将他交给springboot,springboot就会帮我们自动装配
//扩展springmvc dispatchservlet
@Configuration
//@EnableWebMvc 这玩意就是导入了一个类:DelegatingWebMvcConfiguration:从容器中获取所有的webmvcconfig
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/pp").setViewName("test");
}
}
为什么不能有这个注解呢?
我们点进DelegatingWebMvcConfiguration源码
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
// 从容器中获取所有的webmvcConfigurer
@Autowired(required = false)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}
}
}
而在WebMvcAutoConfiguration中有这些条件
所以,一旦映入了 WebMvcConfigurationSupport .class自动装配全面失效!!
所有的WebMvcConfiguration都会被作用,不止Spring自己的配置类,我们自己的配置类当然也会被调用;
全面接管SpringMVC
全面接管即:SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己去配置!
只需在我们的配置类中要加一个@EnableWebMvc。
@EnableWebMvc将WebMvcConfigurationSupport组件导入进来了;
而导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能!