WebMvcConfigurerAdapter与WebMvcConfigurer与WebMvcConfigurationSupport与WebMvcAutoConfiguration添加拦截器

博客介绍了Spring Boot中MVC的4个支持类,包括WebMvcConfigurer、WebMvcConfigurerAdapter、WebMvcConfigurationSupport和WebMvcAutoConfiguration。阐述了在项目中添加拦截器的两种方法及对静态资源访问的影响,指出静态资源访问关键在于WebMvcAutoConfiguration的加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先以上4个类都是springboot中mvc的支持类

  1. WebMvcConfigurer 为接口
  2. WebMvcConfigurerAdapter 是 WebMvcConfigurer 的实现类大部分为空方法 , 已经废除
  3. WebMvcConfigurationSupport 是mvc的基本实现并包含了WebMvcConfigurer接口中的方法
  4. WebMvcAutoConfiguration 是mvc的自动装在类并部分包含了WebMvcConfigurer接口中的方法

如果在springboot项目中没有使用到以上类,那么会自动启用WebMvcAutoConfiguration类做自动加载
项目中的配置都是默认的,比如静态资源文件的访问。

如果项目中要添加自己的拦截器addInterceptors

  • 方法1继承WebMvcConfigurationSupport
    会导致WebMvcAutoConfiguration不加载,所以默认配置丢失导致静态资源等无法访问
@Configuration
public class WebMvc extends WebMvcConfigurationSupport {
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		UserInterceptor userInterceptor = new UserInterceptor();
		registry.addInterceptor(userInterceptor)
				.addPathPatterns("/user/**");
	}
   //添加此方法恢复静态资源访问
   @Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/**")
				.addResourceLocations("classpath:/resources/")
				.addResourceLocations("classpath:/static/")
				.addResourceLocations("classpath:/public/");
	}
}
  • 方法2 实现继承WebMvcConfigurer
    因为是接口实现所以WebMvcAutoConfiguration还会默认配置,所以静态资源是可以访问的
@Configuration
public class WebMvc implements WebMvcConfigurer {
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		UserInterceptor userInterceptor = new UserInterceptor();
		registry.addInterceptor(userInterceptor)
				.addPathPatterns("/user/**");
	}
}

所以现实不现实静态资源关键是在WebMvcAutoConfiguration,如果没有加载就需要自己添加方法,看一下WebMvcAutoConfiguration静态资源加载的方法实现

@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
		TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		if (!this.resourceProperties.isAddMappings()) {
			logger.debug("Default resource handling disabled");
			return;
		}
		Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
		CacheControl cacheControl = this.resourceProperties.getCache()
				.getCachecontrol().toHttpCacheControl();
		if (!registry.hasMappingForPattern("/webjars/**")) {
			customizeResourceHandlerRegistration(registry
					.addResourceHandler("/webjars/**")
					.addResourceLocations("classpath:/META-INF/resources/webjars/")
					.setCachePeriod(getSeconds(cachePeriod))
					.setCacheControl(cacheControl));
		}
		//静态资源  staticPathPattern 值为 /**
		String staticPathPattern = this.mvcProperties.getStaticPathPattern();
		if (!registry.hasMappingForPattern(staticPathPattern)) {
			customizeResourceHandlerRegistration(
					registry.addResourceHandler(staticPathPattern)
							.addResourceLocations(getResourceLocations(
									this.resourceProperties.getStaticLocations()))
							.setCachePeriod(getSeconds(cachePeriod))
							.setCacheControl(cacheControl));
		}
	}
}

// getStaticLocations() 值为
//“classpath:/META-INF/resources/”, “classpath:/resources/”,
//“classpath:/static/”, “classpath:/public/” 跟我们手动配置的一样

soso 希望能帮到你

<think>好的,我现在要回答用户关于Spring Boot中WebMvcConfigurerWebMvcConfigurationSupport的区别的问题。首先,我需要回忆这两个类的作用和它们在Spring Boot中的使用方式。 记得WebMvcConfigurer是一个接口,而WebMvcConfigurationSupport是一个类。用户可能想知道为什么有时候用接口,有时候用继承类。根据引用[1],官方推荐实现WebMvcConfigurer或者继承WebMvcConfigurationSupport。但具体区别是什么? 先看WebMvcConfigurer。这个接口提供了一些默认方法,允许开发者通过重写这些方法来定制MVC配置,比如添加拦截器、格式化器等。实现这个接口不会影响Spring Boot的自动配置,因为Spring Boot会自动检测这些实现。引用[4]中提到,配置视图解析器可以通过重写configureViewResolvers方法,这说明使用WebMvcConfigurer可以保持自动配置的其他部分不变,只修改需要的部分。 然后是WebMvcConfigurationSupport,这是一个基类。当继承它时,需要手动管理所有的MVC配置,因为一旦存在这个类的Bean,Spring Boot的自动配置(比如WebMvcAutoConfiguration)就会失效。引用[3]中的@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)说明,只有当没有WebMvcConfigurationSupport的Bean时,自动配置才会生效。所以使用这个类意味着完全控制MVC配置,但需要自己处理更多配置细节,可能会增加工作量。 适用场景方面,WebMvcConfigurer适合只需要部分定制的情况,而WebMvcConfigurationSupport适合需要完全自定义配置的时候。比如,如果用户只需要添加一个拦截器,用WebMvcConfigurer更方便;但如果要彻底重写所有MVC配置,可能需要继承后者。 另外,需要注意版本差异。在较新的Spring Boot版本中,可能更推荐使用WebMvcConfigurer,因为它自动配置兼容性更好,避免配置冲突。而使用WebMvcConfigurationSupport可能导致一些自动配置失效,需要手动补全其他配置,这可能引入错误或者遗漏。 总结一下,两者的主要区别在于是否保留自动配置,以及配置的灵活性和复杂性。用户需要根据具体需求选择合适的方式。同时,需要提醒用户注意版本兼容性和潜在的配置覆盖问题,确保正确应用这两种方式。</think>在 Spring Boot 中,`WebMvcConfigurer` 和 `WebMvcConfigurationSupport` 都用于自定义 MVC 配置,但它们的实现方式和作用范围有显著差异。以下是核心区别及适用场景: --- ### **1. 核心区别** | **特性** | **WebMvcConfigurer** | **WebMvcConfigurationSupport** | |-------------------------|------------------------------------------------|------------------------------------------------| | **类型** | 接口(Interface) | 抽象类(Abstract Class) | | **自动配置兼容性** | ✅ 保留 Spring Boot 自动配置 | ❌ 覆盖自动配置(需手动管理全部配置)[^3] | | **实现方式** | 实现接口并重写默认方法 | 继承类并重写方法 | | **配置粒度** | 按需覆盖部分配置(如拦截器、视图解析器等) | 完全控制 MVC 配置(需显式定义所有相关组件) | | **版本兼容性** | Spring Boot 推荐方式(兼容性更好)[^1] | 可能因版本升级导致配置失效 | --- ### **2. 适用场景** #### **(1) `WebMvcConfigurer`** - **场景**:需要 **部分定制 MVC 功能**(如添加拦截器、格式化器、跨域配置等),同时保留 Spring Boot 的默认自动配置。 - **示例**: ```java @Configuration public class MyWebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()); } } ``` - **优势**:代码简洁,无需关心其他默认配置的维护[^1][^4]。 #### **(2) `WebMvcConfigurationSupport`** - **场景**:需要 **完全自定义 MVC 配置**,或需要排除某些自动配置(如替换默认的 Jackson 序列化规则)。 - **风险**:继承该类会导致 `WebMvcAutoConfiguration` 自动配置失效,需手动实现所有 MVC 组件[^3]。 - **示例**: ```java @Configuration public class CustomWebMvcConfig extends WebMvcConfigurationSupport { @Override protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new MyCustomConverter()); } } ``` --- ### **3. 关键注意事项** - **自动配置冲突**:若同时存在 `WebMvcConfigurer` 和 `WebMvcConfigurationSupport`,后者会覆盖前者。 - **版本差异**:Spring Boot 2.x 及以上更推荐使用 `WebMvcConfigurer`,因其自动配置的兼容性更好[^4]。 - **代码侵入性**:继承 `WebMvcConfigurationSupport` 会显著增加代码复杂度,需谨慎使用。 --- ### **引用总结** - 官方推荐优先通过 `WebMvcConfigurer` 接口实现定制化,仅在需要完全控制时使用 `WebMvcConfigurationSupport`。 - 使用 `@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)` 注解的自动配置类会在检测到 `WebMvcConfigurationSupport` 时失效。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值