0
我想實現一個Guice模塊,它將一個適配器綁定到一個命名參數,但爲了創建這個適配器,它需要實例化另一個類,它也需要注入參數。Guice綁定一個類和它的適配器
這裏是Scala的例子:
trait Service
class UserService @Inject()(@Named(value = "foo") foo: String) extends Service
trait Adapter
class AdapterImpl(service: Service) extends Adapter
class AdapterRef(val adapter: Adapter)
class Module extends AbstractModule {
override def configure(): Unit = {
val fooValue = "bar"
bind(classOf[String])
.annotatedWith(Names.named("foo"))
.toInstance(fooValue)
val userService = new UserService(fooValue) //It should be instantiated by Guice somehow
bind(classOf[AdapterRef])
.annotatedWith(Names.named("userService"))
.toInstance(new AdapterRef(new AdapterImpl(userService))) //Thats kinda ok
}
}
能有人指出正確的方向?
謝謝
的Gabor
什麼是錯誤? – rethab
沒有錯誤。我需要一個可以替換這行的解決方案:「val userService = new UserService(fooValue)」,因爲我希望系統將所有依賴關係注入到該行中。 –
您創建一個注入器並傳入模塊。然後你從注入器獲得實例。 Google文檔:https://google.github.io/guice/api-docs/3.0/javadoc/com/google/inject/Guice.html – rethab