BeanCurrentlyInCreationException: Error creating bean

启动项目提示错误创建bean问题
  1. 项目启动的时候出现了如下的问题:

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name ‘workerServiceImpl’: Requested bean is currently in creation: Is there an unresolvable circular reference?

翻译过来就是

org.springframework.beans.factory.BeanCurrentlyIncrementationException:创建名为“workerServiceImpl”的bean时出错:请求的bean当前正在创建中:是否存在无法解析的循环引用?

  1. 说明

    根据错误提示已经知道是自己创建bean的时候出现了循环引用,在使用@Autowired的自动注入的时候出现了,比如:A类引用了B类,B类引用了A类

    public class B {
        @Autowired
        private A a;
    }
    
    public class A {
        @Autowired
        private B b;
    }
    

    出现这种代码就会出现以上问题的循环引用错误。

  2. 解决方法
    1. 我们可以去掉循环引用通过容器获取对象,但是不能是成员变量只能是局部变量,如下:

      public class B {
          @Autowired
          private A a;
      }
      
      public class A {
          
          public void method(){
              B b = ApplicationContextHolder.getBean(B.class);
          }
      }
      
      
      去掉循环引用使用时再获取

      这里获取容器的bean方法(这是常用获取bean的方法之一),如下:

      @Component
      public class ApplicationContextHolder implements ApplicationContextAware {
      
            private static ApplicationContext context;
      
            public static <T> T getBean(String name, Class<T> clazz) {
                  return context.getBean(name, clazz);
            }
      
            public static <T> T getBean(Class<T> type) {
                  return context.getBean(type);
            }
      
            public static Object getBean(String clazz) {
                  return context.getBean(clazz);
            }
      
            public static ApplicationContext getContext() {
                  return context;
            }
      
            @Override
            public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
                  ApplicationContextHolder.context = applicationContext;
            }
      
      }
      
    2. 通过懒加载的方式解决问题,如下:

      public class B {
          @Lazy
          @Autowired
          private A a;
      }
      
      public class A {
          @Autowired
          private B b;
      }
      
      
      加上@Lazy在注入的对象中。
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值