事象
アプリケーション起動時に以下のエラーが発生
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| testAService defined in file [/Applications/develop/workspace/awba-management/build/classes/kotlin/main/com/awba/manage/awbamanage/service/testAService.class]
↑ ↓
| testBService defined in file [/Applications/develop/workspace/awba-management/build/classes/kotlin/main/com/awba/manage/awbamanage/service/testBService.class]
└─────┘
原因
testAServiceとtestBServiceクラスでお互いをConstructor Injectionしているため。
Springがどちらのインスタンスを先に作れば良いかわからなくなり、エラーとなる。
testAService.kt
@Service
class TestAService(private val testBService: TestBService){
~
}
testBService.kt
@Service
class TestBService(private val testAService: TestAService){
~
}
解決策
基本的に、お互いを参照するような設計は推奨されてないっぽい。
まずは設計の見直しを検討する。
どうしてもやりたい場合は、@Lazyを使ったりSetter Injectionを使うなどの対応がある
参考
https://www.baeldung.com/circular-dependencies-in-spring
https://stackoverflow.com/questions/40695893/spring-security-circular-bean-dependency