Spring Boot的循环依赖问题

目录

1.循环依赖的概念

2.解决循环依赖的方法

1.构造器方法注入:

2.@Lazy注解

3.@DependsOn注解 


1.循环依赖的概念

        两个或多个bean之间互相依赖,形成循环,此时,Spring容器无法确定先实例化哪个bean,导致循环依赖的问题。

代码示例:

@Service
public class A{

    private B b;
    
    @Autowired
    public A(B b){
        this.b = b;
    }

}

@Service
public class B{

    private A a;

    @Autowired
    public B(A a){
        this.a = a;
    }

}

可以看到代码中,A的对象创建需要先实例化B的对象,而B的对象也需要先实例化A,此时形成了循环依赖。

2.解决循环依赖的方法

1.构造器方法注入:

在构造器中注入,解决循环依赖问题

public class Main {
    public static void main(String[] args) {
        ClassB classB = new ClassB(null);
        ClassA classA = new ClassA(classB);
        classB.setClassA(classA);
    }
}

2.@Lazy注解

@Lazy注解具有延迟加载的功能,能够在需要该bean时再进行实例化

@Service
@Lazy
public class A{

    private B b;
    
    @Autowired
    public A(B b){
        this.b = b;
    }

}

@Service
@Lazy
public class B{

    private A a;

    @Autowired
    public B(A a){
        this.a = a;
    }

}

3.@DependsOn注解 

@DependsOn注解能够指定依赖项的加载顺序,从而避免循环依赖问题

如下代码中:@DependsOn("B")指定了A依赖于B,在实例化A之前,必须先实例化B,避免了循环依赖问题

@Service
@DependsOn("B")
public class A{

    private B b;
    
    @Autowired
    public A(B b){
        this.b = b;
    }

}

@Service
@Lazy
public class B{

    private A a;

    @Autowired
    public B(A a){
        this.a = a;
    }

}

你可能感兴趣的:(spring,boot,java,后端)