アダプタを名前付き引数にバインドする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
}
}
誰かが正しい方向に私を指すことができますか?
はあなたがバインディングを削除することができますあなたのモジュール内Provides方法を使用することができます
ガボール
エラーは何ですか? – rethab
エラーはありません。システムにすべての依存関係を注入したいので、 "val userService = new UserService(fooValue)"という行を置き換えることができる解決策が必要です。 –
インジェクタを作成し、モジュールに渡します。その後、インジェクタからインスタンスを取得します。ドキュメント:https://google.github.io/guice/api-docs/3.0/javadoc/com/google/inject/Guice.html – rethab