Home  >  Article  >  Java  >  Cyclic dependencies in spring boot

Cyclic dependencies in spring boot

Barbara Streisand
Barbara StreisandOriginal
2024-10-22 20:26:03642browse

Dépendances cycliques en spring boot

A cyclical dependency occurs in Java when two classes or two modules depend on each other, thus forming a cycle.

Suppose we have two beans A and B which depend on each other as shown in the example below:

@Component
public class A{
    private final B b;
    public A(B b){
        this.b = b;
    }
}
@Component
public class B{
    private final A a;
    public B(A a){
        this.a = a;
    }
}

When running your project, you will get the following error:

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.

So, to resolve this cyclic dependency, we have four solutions:

  • Refactor code to separate responsibilities.
  • Use intermediate classes or interfaces.
  • Apply dependency injection via methods (setter).
  • Use annotations like @lazy to delay initialization.

In our case, we will use the fourth solution which is just to use the annotation @lazy as shown in the example below:

@Component
public class A{
    private final B b;
    public A(@Lazy B b){
        this.b = b;
    }
}
@Component
public class B{
    private final A a;
    public B(A a){
        this.a = a;
    }
}

And there we are, we are now out of this cycle :)

The above is the detailed content of Cyclic dependencies in spring boot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn