循環依存エラー要求されたBeanは現在作成中です:解決できない循環参照はありますか?



Circular Dependency Error Requested Bean Is Currently Creation



理由

今日プロジェクトに取り組んでいるときにこの落とし穴に遭遇しました。これは文字通り循環依存を引き起こしました。コンストラクターインジェクションを使用していたため、循環依存に遭遇するとエラーが発生しました。図に示すように、依存関係チェーンはループを形成します。
画像

コンストラクタインジェクションが機能しない理由

循環依存を実現するには、AがAを呼び出すときにBを呼び出す必要があり、Bが再びAを呼び出すと、Aは事前にsingletonFactoriesの第3レベルのキャッシュに配置されます。そうしないと、AとBをインスタンス化できません。 singletonFactoriesの3レベルキャッシュを追加するための前提条件は、コンストラクターを実行することです。そのため、コンストラクターによって注入された循環依存関係を解決できず、コンストラクターが書き換えられます。春のソースコードは次のとおりです。



// Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. //Cache singleton bean objects in the container to prevent circular references boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)) if (earlySingletonExposure) { if (logger.isDebugEnabled()) { logger.debug('Eagerly caching bean '' + beanName + '' to allow for resolving potential circular references') } //This is an anonymous inner class, in order to prevent circular references, hold object references as soon as possible addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)) } protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(singletonFactory, 'Singleton factory must not be null') synchronized (this.singletonObjects) { if (!this.singletonObjects.containsKey(beanName)) { this.singletonFactories.put(beanName, singletonFactory)//Three level cache this.earlySingletonObjects.remove(beanName) this.registeredSingletons.add(beanName) } } }

解決

エラーログを表示します。

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'refundSettleRespOneByOneBiz': Requested bean is currently in creation: Is there an unresolvable circular reference?

refundSettleRespOneByOneBizクラスに移動し、コンストラクターインジェクションをセッターインジェクションに変更します
画像
ノードの1つを変更して、循環依存関係を解消します〜