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

Spring Security应用上下文Bean循环依赖问题求助及文档咨询

循环依赖问题解决方案

问题根源

从日志可明确循环依赖链:

webSecurityConfiguration → userDetailsService → BCryptPasswordEncoder(由webSecurityConfiguration定义)→ webSecurityConfiguration

WebSecurityConfiguration初始化时需要注入UserDetailsService,而UserDetailsService初始化依赖BCryptPasswordEncoder;同时WebSecurityConfiguration的configurePasswordEncoder方法直接调用getBCryptPasswordEncoder()创建Bean,触发了循环依赖。

修复方案

方案一:修改密码编码器的注入方式

调整WebSecurityConfiguration中的configurePasswordEncoder方法,通过Spring注入BCryptPasswordEncoder,而非直接调用@Bean方法:

@Autowired
public void configurePasswordEncoder(AuthenticationManagerBuilder builder, BCryptPasswordEncoder passwordEncoder) throws Exception{
    builder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}

方案二:将密码编码器Bean移至独立配置类

创建单独的配置类定义BCryptPasswordEncoder,让WebSecurityConfiguration和UserDetailsService都依赖这个独立Bean:

@Configuration
public class SecurityBeanConfig {
    @Bean
    public BCryptPasswordEncoder getBCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

随后删除WebSecurityConfiguration中的getBCryptPasswordEncoder()方法,确保两个类均通过@Autowired注入该Bean。

优质文档推荐

  • Spring官方文档循环依赖处理章节:讲解Spring循环依赖的处理逻辑,以及避免循环的最佳实践
  • Spring Security官方文档Bean配置部分:指导Security相关Bean的正确配置方式,减少依赖冲突
  • Spring核心技术文档依赖注入模块:深入理解DI机制,从根源规避循环依赖问题

内容的提问来源于stack exchange,提问作者Ömer Atayilmaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:40:33