WebMvcConfigurationSupport 详解

xdqx / 2023-08-08 / 原文

1、首先区分四个MVC配置类

  四个MVC配置类的关系
  WebMvcConfigurerAdapter
  WebMvcConfigurer
  WebMvcConfigurationSupport
  WebMvcAutoConfiguration

①WebMvcConfigurer 为接口

②WebMvcConfigurerAdapter 是 WebMvcConfigurer 的实现类大部分为空方法(一般用不到),是 WebMvcConfigurer的子类实现,由于Java8中可以使用default关键字为接口添加默认方法,为在源代码中spring5.0之后就已经弃用本类,如果需要我接着可以实现WebMvcConfigurer类。

③WebMvcConfigurationSupport 是mvc的基本实现并包含了WebMvcConfigurer接口中的方法
④WebMvcAutoConfiguration 是mvc的自动装在类并部分包含了WebMvcConfigurer接口中的方法
如果在springboot项目中没有使用到以上类,那么会自动启用WebMvcAutoConfiguration类做自动加载;项目中的配置都是默认的,比如静态资源文件的访问


2、WebMvcConfigurationSupport 对应的方法

  /** 解决跨域问题 **/
void addCorsMappings(CorsRegistry registry) ;
   /** 添加拦截器 **/
void addInterceptors(InterceptorRegistry registry);
  /** 视图跳转控制器 **/
void addViewControllers(ViewControllerRegistry registry);
/** 这里配置视图解析器 **/
void configureViewResolvers(ViewResolverRegistry registry);
 /** 配置内容裁决的一些选项 **/
void configureContentNegotiation(
       ContentNegotiationConfigurer configurer);
   /** 视图跳转控制器 **/
void addViewControllers(
        ViewControllerRegistry registry);
  /** 静态资源处理 避免静态资源被拦截**/
void addResourceHandlers(
       ResourceHandlerRegistry registry);
    /** 默认静态资源处理器 **/
void configureDefaultServletHandling(
    DefaultServletHandlerConfigurer configurer);

3、MVC最佳实践

方式1:@EnableWebMvc
方式2: 继承WebMvcConfigurationSupport 但是没有汇集项目中WebMvcConfigure接口实现类的功能的

可以在配置类加上@EnableWebMvc注解之外,也可以直接继承WebMvcConfigurationSupport,而不使用@EnableWebMvc注解,因为@EnableWebMvc内部也是使用WebMvcConfigurationSupport来完成SpringMVC默认配置的添加的。

如果项目中没有通过使用WebMvcConfigurer接口的实现类来提供SpringMVC的配置,则可以只使用一个WebMvcConfigurationSupport的子类来启动和自定义SpringMVC的功能。因为@EnableWebMvc其实还有一个功能是汇集项目中所有实现了WebMvcConfigurer接口的类

版权声明:本文为CSDN博主「下自成蹊*」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zpx_Smart/article/details/124559942