Guice proxying to support circular dependency

后端 未结 3 1304
伪装坚强ぢ
伪装坚强ぢ 2021-02-19 20:40

I\'m getting the following error in my code at launch:

Tried proxying com.bar.Foo to support a circular dependency, but it is not an interface.

3条回答
  •  误落风尘
    2021-02-19 21:00

    Here is @jan-galinski's answer, redone in Scala:

    import javax.inject.Inject
    import com.google.inject.{Guice, Injector, Provider}
    import net.codingwell.scalaguice.InjectorExtensions._
    
    /** Demonstrates the problem by failing with `Tried proxying CircularDep1$A to support a circular dependency, but it is not an interface.
      while locating CircularDep1$A for parameter 0 at CircularDep1$B.(CircularDep.scala:10)
      while locating CircularDep1$B for parameter 0 at CircularDep1$A.(CircularDep.scala:6)
      while locating CircularDep1$A` */
    object CircularDep1 extends App {
      class A @Inject() (val b: B) {
        val name = "A"
      }
    
      class B @Inject() (val a: A) {
        val name = "B"
      }
    
      val injector: Injector = Guice.createInjector()
      val a: A = injector.instance[A]
      val b: B = injector.instance[B]
    
      assert("A" == a.name)
      assert("B" == a.b.name)
      assert("B" == b.name)
      assert("A" == b.a.name)
      println("This program won't run!")
    }
    
    /** This version solves the problem by using `Provider`s */
    object CircularDep2 extends App {
      class A @Inject() (val b: Provider[B]) {
        val name = "A"
      }
    
      class B @Inject() (val a: Provider[A]) {
        val name = "B"
      }
    
      val injector: Injector = Guice.createInjector()
      val a: A = injector.instance[A]
      val b: B = injector.instance[B]
    
      assert("A" == a.name)
      assert("B" == a.b.get.name)
      assert("B" == b.name)
      assert("A" == b.a.get.name)
      println("Yes, this program works!")
    }
    

提交回复
热议问题