首頁  >  文章  >  Java  >  Spring Boot中的循環依賴

Spring Boot中的循環依賴

Barbara Streisand
Barbara Streisand原創
2024-10-22 20:26:03648瀏覽

Dépendances cycliques en spring boot

Java 中的循環依賴是指兩個類別或兩個模組相互依賴,從而形成循環。

假設我們有兩個相互依賴的 bean A 和 B,如下例所示:

@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;
    }
}

運行專案時,會出現以下錯誤:

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.

因此,為了解決這種循環依賴,我們有四種解決方案:

  • 重構程式碼以分離職責。
  • 使用中間類別或介面。
  • 透過方法(setter)應用依賴注入。
  • 使用 @lazy 等註解來延遲初始化。

在我們的例子中,我們將使用第四個解決方案,即使用註釋@lazy,如下例所示:

@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;
    }
}

我們現在已經脫離了這個循環:)

以上是Spring Boot中的循環依賴的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn