【已解决】启动项目后提示缺少:A component required a bean of type 'org.springframework.web.filter.CorsFilter' that could not be found.
- 工作小总结&小工具类
- 时间:2025-05-01 06:39
- 22人已阅读
🔔🔔好消息!好消息!🔔🔔
有需要的朋友👉:微信号
背景描述:
Spring boot项目在未配置使用Spring Security前可以正常启动,但是使用Spring Security之后启动就报错了。
产生问题原因分析及解决方案:
根据错误提示,应用缺少CorsFilter的Bean定义,以下是解决方案:
1. 添加全局CORS配置类
创建一个配置类以显式定义CorsFilter的Bean:
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 允许所有接口跨域 .allowedOrigins("*") // 允许所有来源 .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的方法 .allowedHeaders("*") // 允许所有请求头 .exposedHeaders("Authorization"); // 暴露给前端的头部 } }
2. 若使用Spring Security,需额外配置
如果项目中引入了Spring Security,默认的CORS配置会被覆盖,需在安全配置中显式启用:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() // 启用CORS .csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } // 显式注入CORS配置 @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("*")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
3. 检查依赖版本兼容性
确认是否因Spring Boot版本升级导致CORS自动配置失效:
若使用Spring Boot 2.4+,需确保spring-web模块版本与Spring Boot主版本兼容。
检查pom.xml或build.gradle中是否意外排除了spring-web相关依赖。
4. 排除冲突配置
如果其他第三方库(如Shiro、JWT)自行管理了CORS,可能导致与Spring的CORS配置冲突。可尝试:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, WebMvcAutoConfiguration.class})
但需谨慎,避免过度排除自动配置。
5. 临时解决方案(不推荐)
若需快速验证问题,可在启动类添加@SpringBootApplication的exclude参数:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, CorsAutoConfiguration.class})
但此方法可能引入其他问题,建议优先使用第1或第2种规范方案。
总结: 该错误本质是Spring Boot未检测到CORS配置,需通过显式配置CorsFilter或启用Spring Security的CORS支持解决。建议优先使用WebMvcConfigurer实现全局配置。
上一篇: 在ChirpStack中查看设备和数据(网关上线、设备上线、查看数据报文)
下一篇: 返回列表