首頁 > Java > java教程 > 主體

Spring Boot中的循環依賴

Barbara Streisand
發布: 2024-10-22 20:26:03
原創
648 人瀏覽過

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!