
本文详解 Spring Boot 应用中 @SpringBootApplication 类内嵌 CORS 配置与独立 WebConfig 类的冲突问题,指出 WebMvcConfigurerAdapter 已废弃,并推荐基于 WebMvcConfigurer 的标准配置方式及更优的 Security 集成路径。
本文详解 spring boot 应用中 `@springbootapplication` 类内嵌 cors 配置与独立 `webconfig` 类的冲突问题,指出 `webmvcconfigureradapter` 已废弃,并推荐基于 `webmvcconfigurer` 的标准配置方式及更优的 security 集成路径。
在 Spring Boot 项目中,你可能会遇到多个地方定义了 CORS(跨域资源共享)配置,例如同时在主启动类 MyApplication 中声明 WebMvcConfigurer Bean,又在单独的 WebConfig 类中继承(已废弃的)WebMvcConfigurerAdapter。这种重复不仅冗余,还易引发配置覆盖、优先级混乱甚至运行时异常。
首先,WebMvcConfigurerAdapter 自 Spring Framework 5.0 起已被正式标记为 @Deprecated,并在 Spring Boot 2.7+ 及 Spring Framework 6.x 中完全移除。因此,以下写法应立即弃用:
@Configuration
@EnableWebMvc // ⚠️ 通常也不推荐,除非需完全接管 MVC 配置
public class WebConfig extends WebMvcConfigurerAdapter { // ❌ 已废弃
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}✅ 正确做法是:仅保留一个 @Configuration 类,实现 WebMvcConfigurer 接口(无需继承任何基类),并建议添加 @Configuration(proxyBeanMethods = false) 提升启动性能:
@Configuration(proxyBeanMethods = false)
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("https://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600);
}
}⚠️ 同时,请删除 MyApplication 类中 corsConfigurer() 方法——该方法会注册一个额外的 WebMvcConfigurer Bean,与 WebConfig 冲突,且缺乏细粒度控制(如未设置 allowedOrigins,默认仅允许 null 源,实际无法通过浏览器预检)。Spring Boot 的自动配置机制会自动收集所有 WebMvcConfigurer 实现,无需手动注册。
? 更进一步的最佳实践:
若项目已集成 Spring Security(尤其使用 SecurityFilterChain),推荐将 CORS 配置统一交由 Security 管理,而非 MVC 层。因为 CORS 预检请求(OPTIONS)不经过 MVC 的 DispatcherServlet,而由 Security 过滤器链前置处理,能确保真正生效:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> cors.configurationSource(corsConfigurationSource())) // ✅ 委托给 CorsConfigurationSource
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/**").authenticated()
.anyRequest().permitAll()
);
return http.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowCredentials(true);
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}✅ 总结:
- 删除所有
WebMvcConfigurerAdapter相关代码; - 仅保留一个
WebMvcConfigurer实现类(如WebConfig),用于非 Security 场景或补充资源处理器等; - 若使用 Spring Security,优先通过
HttpSecurity.cors()配置 CORS,保障预检请求正确拦截与响应; - 避免在
@SpringBootApplication类中定义WebMvcConfigurerBean,防止隐式重复注册。
这样既能保证配置清晰、可维护,又能兼容 Spring Boot 最新版本演进。


















