
Spring Boot 应用中不应同时在启动类和独立配置类中定义 CORS,WebMvcConfigurerAdapter 已废弃,推荐统一使用 WebMvcConfigurer 接口实现,并优先考虑通过 SecurityFilterChain 进行细粒度控制。
spring boot 应用中不应同时在启动类和独立配置类中定义 cors,`webmvcconfigureradapter` 已废弃,推荐统一使用 `webmvcconfigurer` 接口实现,并优先考虑通过 securityfilterchain 进行细粒度控制。
在 Spring Boot 2.4+(尤其是基于 Spring Framework 5.3+)中,WebMvcConfigurerAdapter 已被正式标记为 @Deprecated 并彻底移除——它曾是为兼容旧版抽象类设计的过渡方案,现已完全由函数式接口 WebMvcConfigurer 取代。因此,您当前代码中的 WebConfig 类继承 WebMvcConfigurerAdapter 是不合法且无法编译的(若使用较新版本),必须重构为 implements WebMvcConfigurer。
更关键的是:MyApplication 类中定义的 corsConfigurer() 方法虽能生效,但属于反模式。Spring Boot 的自动配置机制会扫描所有 @Configuration 类中返回 WebMvcConfigurer 的 @Bean 方法,而将配置逻辑耦合在启动类中,会降低可维护性、违反单一职责原则,也不利于模块化测试与复用。
✅ 正确做法如下:
-
删除启动类中的
corsConfigurer()方法(即MyApplication中的冗余 Bean 定义); -
重写
WebConfig为标准配置类,并启用@Configuration(无需@EnableWebMvc,除非你明确要禁用 Spring Boot 的 MVC 自动配置):
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("https://example.com", "http://localhost:3000")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600);
}
}⚠️ 注意事项:
- 若项目已集成 Spring Security,更推荐在
SecurityFilterChain中统一管理 CORS(尤其涉及认证/凭证时),因为 Security 的 CORS 处理优先级更高,且能与 CSRF、认证流程无缝协同:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> cors.configurationSource(request -> {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("https://example.com"));
config.setAllowedMethods(Arrays.asList("GET", "POST"));
config.setAllowCredentials(true);
return config.applyPermitDefaultValues();
}))
.authorizeHttpRequests(authz -> authz
.requestMatchers("/api/**").authenticated()
.anyRequest().permitAll()
);
return http.build();
}-
@EnableWebMvc会完全禁用 Spring Boot 的WebMvcAutoConfiguration,导致静态资源处理、消息转换器、视图解析等自动配置失效,仅在需深度定制 MVC 行为时才应启用——普通 CORS 配置无需它。
总结:保持配置集中、语义清晰、符合演进规范。优先使用 WebMvcConfigurer 实现类管理跨域,但在安全敏感场景下,应交由 SecurityFilterChain 统一管控,确保 CORS 策略与整体安全策略一致。


















