Spring Boot 3.0.1配置登录时HttpSecurity Bean创建失败求助
问题分析与解决方案
核心问题
ClassNotFoundException: org.springframework.security.core.context.DeferredSecurityContext 本质是Spring Security版本依赖冲突:Spring Boot 3.0.1对应Spring Security 6.0.x版本,而DeferredSecurityContext在Spring Security 6.x中已被移除/重构,若项目中混入5.x版本的Spring Security核心依赖,就会触发类找不到的错误。
解决方案步骤
1. 排查并清理依赖冲突
执行Maven命令查看依赖树,定位所有低版本Spring Security依赖:
mvn dependency:tree | grep spring-security
若发现5.x版本的依赖,在对应依赖节点中添加排除规则:
<exclusion> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> </exclusion>
确保所有Spring Security相关依赖都继承自Spring Boot父项目的6.x版本。
2. 清理本地Maven缓存
删除本地仓库中Spring Security的缓存文件,避免旧版本残留:
# Linux/Mac系统 rm -rf ~/.m2/repository/org/springframework/security # Windows系统 rd /s /q %USERPROFILE%\.m2\repository\org\springframework\security
重新拉取依赖:
mvn clean install -U
3. 修复配置类的实现问题
你的UserProfile类中有两个方法未添加@Override注解,可能导致运行时类实现不匹配,补充注解:
@Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; }
4. 优化Security配置(可选)
原配置中存在重复的授权规则,anyRequest().permitAll()会覆盖后续的hasRole("ADMIN")规则,调整为链式写法更清晰:
@Bean protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .httpBasic() .and() .cors() .and() .authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.GET, "/paciente").hasRole("ADMIN") .anyRequest().authenticated() ) .authenticationProvider(authProvider()) .logout(logout -> logout .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)) ) .csrf().disable(); return http.build(); }
验证
重新启动项目,若依赖冲突解决,httpSecurity Bean将正常初始化,登录功能可正常运行。
内容的提问来源于stack exchange,提问作者BeatrizGomes
相关产品推荐
相关产品推荐

