Spring对循环依赖注入的处理

默认单实例情况下,通过字段循环依赖不会报错,可以互相依赖

@Component
public class BeanA {
    
    
    private static final Logger logger = LoggerFactory.getLogger(BeanA.class);

    @Autowired
    private BeanB beanB;

    public void print() {
    
    
        logger.info("hello springboot !");
    }
}

@Component
public class BeanB {
    
    
    private static final Logger logger = LoggerFactory.getLogger(BeanB.class);

    @Autowired
    private BeanA beanA;

    public void print() {
    
    
        logger.info("hello springboot !");
    }
}

构造循环依赖启动时直接报错

异常信息:

  The dependencies of some of the beans in the application context form a cycle:
 
   ┌─────┐
   |  beanA defined in file [D:\workspaces\demo\target\classes\com\example\demo\bean2\BeanA.class]
   ↑     ↓
   |  beanB defined in file [D:\workspaces\demo\target\classes\com\example\demo\bean2\BeanB.class]
   └─────┘
@Component
public class BeanA {
    
    
    private static final Logger logger = LoggerFactory.getLogger(BeanA.class);

    private BeanB beanB;

    public BeanA(BeanB beanB) {
    
    
        this.beanB = beanB;
    }

    public void print() {
    
    
        logger.info("hello springboot !");
    }
}

@Component
public class BeanB {
    
    
    private static final Logger logger = LoggerFactory.getLogger(BeanB.class);

    private BeanA beanA;

    public BeanB(BeanA beanA) {
    
    
        this.beanA = beanA;
    }

    public void print() {
    
    
        logger.info("hello springboot !");
    }
}

非单例循环依赖,启动时不会报错,但是获取bean时会报错

异常信息: Requested bean is currently in creation: Is there an unresolvable circular reference?

@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class BeanA {
    
    
    private static final Logger logger = LoggerFactory.getLogger(BeanA.class);

    @Autowired
    private BeanB beanB;

    public void print() {
    
    
        logger.info("hello springboot !");
    }
}

@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class BeanB {
    
    
    private static final Logger logger = LoggerFactory.getLogger(BeanB.class);

    @Autowired
    private BeanA beanA;

    public void print() {
    
    
        logger.info("hello springboot !");
    }
}

测试代码

@SpringBootApplication
public class DemoApplication {
    
    
    private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class);

    public static void main(String[] args) throws Exception {
    
    
        ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);

        BeanA bean = context.getBean(BeanA.class);
        bean.print();
    }
}

猜你喜欢

转载自blog.csdn.net/u013202238/article/details/107879765