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

升级Spring Boot 2.6后出现BeanCurrentlyInCreationException异常如何解决

异常原因分析
  • Spring Boot 2.6.0版本默认禁用了循环引用自动处理,该默认规则是框架版本升级带来的变更,低于2.6.0的版本默认允许自动处理循环引用,因此相同代码在旧版本不会触发报错。
  • 你的代码存在隐性循环依赖:WebSecurityConfig配置类实例化时,需要优先执行被@Autowired标注的configureGlobal方法,该方法内部调用了本类定义的非静态@Bean方法encoder()获取PasswordEncoder实例;而非静态的@Bean方法需要配置类本身实例化完成后才能被调用创建对应Bean,二者互相等待触发循环引用异常。
修复方案

你可以任选以下任意一种方案修复问题:

  1. 拆分PasswordEncoder到独立配置类(推荐)
    将PasswordEncoder的Bean定义移到单独的配置类中,避免同一个配置类内的循环依赖:
// 单独的配置类
@Configuration
public class SecurityBeanConfig {
    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }
}

之后删除WebSecurityConfig类中的encoder()方法即可。

  1. 声明PasswordEncoder的Bean方法为静态
    将encoder()方法修改为静态,静态@Bean方法不需要配置类实例化即可创建对应Bean,不会触发循环依赖:
@Bean
public static PasswordEncoder encoder() {
    return new BCryptPasswordEncoder();
}
  1. 改用父类的configure重载方法
    删除@Autowired标注的configureGlobal方法,改为重写父类WebSecurityConfigurerAdapter提供的configure(AuthenticationManagerBuilder auth)方法,不需要额外注入即可生效:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
        .withUser("testuser")
        .password(encoder().encode("password"))
        .roles("READ");
}
  1. 临时开启循环引用支持(不推荐)
    在项目配置文件(application.properties/application.yml)中添加配置,重新开启循环引用自动处理,属于规避问题的临时方案:
spring.main.allow-circular-references=true

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:27:02