You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security配置AuthenticationManager出现循环依赖报错

问题根因

循环依赖来自SecurityConfig类内部的自引用逻辑冲突:

  • 你在类中通过@Autowired标记AuthenticationManager字段,要求Spring初始化SecurityConfig时必须先注入这个Bean才能完成实例化
  • 同时你又在同一个类中通过@Bean标记authenticationManagerBean()方法,声明AuthenticationManager这个Bean本身由SecurityConfig负责生产
    Spring初始化Bean时会先完成依赖注入再执行Bean生产逻辑,这就导致SecurityConfig等AuthenticationManager注入、AuthenticationManager等SecurityConfig生产的死循环,直接触发启动报错。
修复步骤
  1. 删除SecurityConfig类中冗余的AuthenticationManager字段注入代码,也就是移除以下两行:
@Autowired
private AuthenticationManager authenticationManager;
  1. 修改buildUsernamePasswordAuthFilter方法,不再依赖注入的字段,直接调用本类提供的authenticationManagerBean()方法获取实例,注意给方法签名加上异常抛出声明避免编译报错:
protected UsernamePasswordAuthenticationFilter buildUsernamePasswordAuthFilter(String loginEntryPoint) throws Exception {
    UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(loginEntryPoint, successHandler, failureHandler, objectMapper);
    filter.setAuthenticationManager(authenticationManagerBean());
    return filter;
}
补充说明
  • 你提供的自定义认证过滤器、认证Provider、认证成功/失败处理器代码均无逻辑问题,不需要调整。
  • 不建议通过配置spring.main.allow-circular-references=true的方式绕过报错,这只是Spring提供的临时兼容手段,没有从代码结构上消除循环依赖,后续版本升级、功能迭代时容易触发隐性问题。

内容的提问来源于stack exchange,提问作者Antonblue16

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 08:54:22