
本文详解 Spring Boot 项目中为何不应同时在启动类和独立配置类中定义 CORS,指出 WebMvcConfigurerAdapter 已废弃,并提供符合现代 Spring Boot(2.4+)规范的单一、清晰、可维护的 CORS 配置方式。
本文详解 spring boot 项目中为何不应同时在启动类和独立配置类中定义 cors,指出 `webmvcconfigureradapter` 已废弃,并提供符合现代 spring boot(2.4+)规范的单一、清晰、可维护的 cors 配置方式。
在 Spring Boot 应用中,CORS(跨域资源共享)配置应保持唯一、明确且符合框架演进规范。您当前代码中存在两处 CORS 配置:一处位于主启动类 MyApplication 中通过 @Bean WebMvcConfigurer 方法声明,另一处在 WebConfig 类中继承已废弃的 WebMvcConfigurerAdapter。这不仅造成逻辑冗余,更可能引发配置冲突或被忽略——因为 Spring Boot 会自动收集所有 WebMvcConfigurer 类型的 Bean 并合并其配置,但混合使用新旧模式会降低可读性与可维护性。
首先,WebMvcConfigurerAdapter 自 Spring Framework 5.0 起已被标记为 @Deprecated,并在 Spring Boot 2.4+ 中彻底移除。因此,WebConfig 必须重构为直接实现 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);
}
}其次,不建议在 @SpringBootApplication 主类中定义 WebMvcConfigurer Bean(如 corsConfigurer() 方法)。原因有三:
- 违反关注点分离原则:启动类应专注应用生命周期管理,而非具体 Web 层配置;
- 不利于模块化:CORS 配置分散后难以统一审查与复用;
- 容易被覆盖:若多个
@Bean WebMvcConfigurer存在,虽会合并,但调试复杂度上升。
此外需注意:若项目已集成 Spring Security,更推荐将 CORS 配置交由 SecurityFilterChain 统一管理(尤其涉及认证/凭证时),因其能与安全策略协同生效,避免预检请求(OPTIONS)被安全过滤器拦截:
@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", "PUT", "DELETE"));
config.setAllowCredentials(true);
return config.applyPermitDefaultValues();
}))
.authorizeHttpRequests(authz -> authz
.requestMatchers("/api/**").authenticated()
.anyRequest().permitAll()
);
return http.build();
}✅ 最佳实践总结:
- ✅ 仅保留一个
@Configuration类实现WebMvcConfigurer,用于基础静态资源、路径映射等通用 Web 配置; - ✅ 若启用 Spring Security,优先通过
HttpSecurity.cors()配置 CORS,确保与认证流程一致; - ❌ 删除
WebMvcConfigurerAdapter及其子类; - ❌ 避免在启动类中声明
WebMvcConfigurerBean; - ? 使用
@Profile或条件注解(如@ConditionalOnMissingBean)进一步保障配置唯一性。
遵循以上方式,您的 CORS 配置将更健壮、可测试、易演进。


















