Spring Boot 循环依赖发生在字段和 setter 注入中

问题描述 投票:0回答:1

我读过,为了解决循环依赖,我们应该使用 setter 或字段注入。 我尝试了两者,但仍然遇到同样的问题。我正在使用 spring boot 应用程序:java17/spring 3.1.5.

  1. 二传手注射

豆A

@Component
public class BeanA {

    BeanA() {
        System.out.println("BeanA constructor called !!!");
    }

    private BeanB beanB;

    @Autowired
    public void setBeanB(BeanB beanB) {
        System.out.println("Setting property beanB of BeanA instance");
        this.beanB = beanB;
    }
}

豆B

@Component
public class BeanB {

BeanB() {
        System.out.println("BeanB constructor called !!!");
    }

    private BeanA beanA;

    @Autowired
    public void setBeanA(BeanA beanA) {
        System.out.println("Setting property beanA of BeanB instance");
        this.beanA = beanA;
    }
}
  1. 现场注入

豆A

@Component
public class BeanA {

    @Autowired
    BeanB beanB;

    BeanA(){
//        System.out.println("beanA init!");
    }
}

豆B

@Component
public class BeanB {

    @Autowired
    BeanA beanA;

    BeanB(){
        System.out.println("beanB init!");
    }
}

对于这两个示例,我都收到以下错误

**************************
APPLICATION FAILED TO START
***************************

Description:

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  beanA
↑     ↓
|  beanB
└─────┘


Action:

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.

下面是应用程序的层次结构

com.demo.example
MainApp.java
setterInjection
..beanA
..beanB
fieldIjection
..beanA
..beanB
java spring spring-boot java-17 spring-3
1个回答
0
投票

您可以尝试在 application.properties/yaml 文件中添加以下值: spring.main.allow-circular-references=true

© www.soinside.com 2019 - 2024. All rights reserved.