自定义扩展视图解析器
步骤:
- 定义一个控制类
- 该类实现webMvcConfiger接口,可以通过重写方法,来实现自定义功能
- 自定义视图解析器(静态内部类):实现ViewResoler接口,将视图解析器交给springboot管理,实现ViewResoler接口的类就是视图解析器
//扩展视图解析器
@Controller
public class MyMvcConfig implements WebMvcConfigurer {
@Bean
private ViewResolver MyViewResolver(){
return new MyViewResolver();
}
// 自定义视图解析器
public static class MyViewResolver implements ViewResolver{
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return null;
}
}
}
- 测试 dispatcherServlet->doDispatch(打断点)
0、1是springboot自带的视图解析器,2是thymeleaf自带的视图解析器,3是自定义的视图解析器
实现转发功能
@Controller
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/test_mvc").setViewName("index");
}
}
注意:
在WebMvcAutoConfiguration中有这样这个注解
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
含义是如果已经配置了该类,则所有的自动配置都不会生效
@EnablewebMvc:自动导入了一个类DelegatingWebMvcConfiguration,它是WebMvcConfigurationSupport的子类
所以配置MVC扩展的时候不要使用@EnablewebMvc
总结:
- 自动装配的过程:springboot遍历所有视图解析器选择最适合的视图解析器去使用
- xxxCongigurer :是springboot的扩展配置



