Home > Java > javaTutorial > body text

Cyclic dependencies in spring boot

Barbara Streisand
Release: 2024-10-22 20:26:03
Original
648 people have browsed it

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;
    }
}
Copy after login
@Component
public class B{
    private final A a;
    public B(A a){
        this.a = a;
    }
}
Copy after login
Copy after login

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.
Copy after login

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;
    }
}
Copy after login
@Component
public class B{
    private final A a;
    public B(A a){
        this.a = a;
    }
}
Copy after login
Copy after login

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!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!