たとえば、私は
@Service
public class UserSerice {
@Autowired
private HouseService houseService;
}
と
@Service
public class HouseService {
@Autowired
private UserSerice userService;
}
Spring はこれをどのように自動配線しますか? そして、この方法で Bean を構成することは良い習慣ですか?
Circular dependencies (spring-framework-reference):
For example: Class A requires an instance of class B through constructor injection, and class B requires an instance of class A through constructor injection...throws a BeanCurrentlyInCreationException.
it is not recommended... One possible solution is to edit the source code of some classes to be configured by setters rather than constructors...
PLUS:
I debugged the circular dependencies in setter way. The sequence seems that:
-> Start to create bean A
-> Start to create bean B
-> Inject A to B, although A is not created fully from perspective of Spring lifecycle
-> Bean B creation finish
-> Inject bean B to A
-> Bean A created
これはコンストラクターインジェクションではないため、Springは両方のオブジェクトを安全にインスタンス化し、それらの依存関係を満たすことができます。アーキテクチャ的には、このようなケースはいわゆる「コードの臭い」と呼ばれます。構図に何か問題があることを示しています。ロジックを移動する必要があるかもしれませんし、サードクラスを導入する必要があるかもしれません。
これらの規約については Google
フライ級パターン
Java での循環依存
2 つの Java オブジェクトが相互に参照できるように、このような構成は完全に有効です。