Spring Boot中两个CORS配置类的必要性咨询
Spring Boot重复CORS配置的疑问解析
我的Spring Boot应用里有两个都配置了CORS的类:MyApplication和WebConfig。我猜测其中一个是多余的,想请教为何会同时存在这两个配置?
MyApplication 代码
@EntityScan("com.nz.myapp") @SpringBootApplication(exclude = {SecurityAutoConfiguration.class }) public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"); } }; } }
WebConfig 代码
@Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"); } }
核心结论:这两个配置完全重复,且WebConfig的写法存在不合理之处
两种配置的差异
MyApplication中的配置:
这是Spring Boot推荐的轻量配置方式——在主类中直接定义WebMvcConfigurer类型的Bean,无需额外的@Configuration或@EnableWebMvc注解。Spring Boot会自动识别并合并这个自定义配置到它的WebMvc自动配置体系中,不会破坏原有自动配置的特性。WebConfig中的配置:
- 这个类使用了
@EnableWebMvc,这会直接禁用Spring Boot的WebMvc自动配置,强制切换为全手动的Spring MVC配置模式,违背了Spring Boot"约定大于配置"的设计理念,会导致静态资源访问、消息转换器自动配置等特性失效。 - 它继承的
WebMvcConfigurerAdapter在Spring 5及以上版本已被标记为过时,官方推荐直接实现WebMvcConfigurer接口。 - 里面的CORS配置逻辑和主类中的完全一致,属于冗余配置。
- 这个类使用了
为何会同时存在?
- 开发者习惯差异:部分开发者偏好将配置抽离到单独的配置类,另一部分则习惯在主类中快速实现简单配置,若缺乏代码同步或清理,就会出现重复。
- 历史遗留问题:可能最初采用了WebConfig的配置方式,后续在主类中追加CORS配置后,遗忘删除旧的配置类。
- 对Spring Boot自动配置机制不熟悉:不清楚
@EnableWebMvc的副作用,也不知道主类中定义WebMvcConfigurerBean即可生效,导致重复配置。
优化建议
- 优先保留MyApplication中的配置,直接删除WebConfig类:这种方式既简洁,又能保留Spring Boot的自动配置优势。
- 若坚持使用单独配置类,修改WebConfig:去掉
@EnableWebMvc注解,将继承WebMvcConfigurerAdapter改为实现WebMvcConfigurer接口,同时删除主类中的重复配置。
内容的提问来源于stack exchange,提问作者Radika Moonesinghe
相关产品推荐
相关产品推荐

