java - 动态注入(inject) Google Guice bean

标签 java dependency-injection guice

我正在将构造函数 DI 与 Google Guice 结合使用。

public class MyClass {

    private MyOtherClass otherclass

    @Inject
    MyClass(MyOtherClass otherClass) {
         this.otherClass = otherClass
    }
}

要获取 MyClass 的实例,我这样做:

com.google.inject.Injector.getInstance(MyClass.class)

一切都好。但是,现在我有两个不同版本的 MyOtherClass。所以我需要这样的东西:

public class MyClass {

    MyInterface myInterface

    @Inject
    MyClass(MyInterface myOtherInterface) {
         this.myOtherInterface = myOtherInterface;
    }
}

}

我需要能够在运行时实例化一个 MyClassMyOtherClassAMyOtherClassB 实例。

所以在一个代码路径中我需要类似的东西:

 com.google.inject.Injector.getInstance(MyClass.class, MyOtherClassA)   // A myClass sinstance which points to MyOtherClassA

在另一个代码路径中,我需要:

 com.google.inject.Injector.getInstance(MyClass.class, MyOtherClassB)   // A myClass sinstance which points to MyOtherClassB

我该怎么做?

最佳答案

有两种方法可以实现这一点

  • Binding Annotations

创建以下 Annotations 类

public class Annotations {
  @BindingAnnotation
  @Target({FIELD, PARAMETER, METHOD})
  @Retention(RUNTIME)
  public @interface ClassA {}

  @BindingAnnotation
  @Target({FIELD, PARAMETER, METHOD})
  @Retention(RUNTIME)
  public @interface ClassB {}
}

在模块类中添加绑定(bind)

bind(MyInterface.class).annotatedWith(ClassA.class).toInstance(new MyOtherClassA());
bind(MyInterface.class).annotatedWith(ClassB.class).toInstance(new MyOtherClassB());

要获取必要的实例,请使用此

injector.getInstance(Key.get(MyInterface.class, ClassA.class))
injector.getInstance(Key.get(MyInterface.class, ClassB.class))

MyClass 构造函数将如下所示

@Inject
MyClass(@ClassA MyInterface myOtherInterface) {
   this.myOtherInterface = myOtherInterface;
}
  • @Named

使用以下绑定(bind)

bind(MyInterface.class).annotatedWith(Names.named("MyOtherClassA")).toInstance(new MyOtherClassA());
bind(MyInterface.class).annotatedWith(Names.named("MyOtherClassB")).toInstance(new MyOtherClassB());

要获取实例,请使用此

injector.getInstance(Key.get(MyInterface.class, Names.named("MyOtherClassA")))
injector.getInstance(Key.get(MyInterface.class, Names.named("MyOtherClassB")))

MyClass 构造函数将如下所示

@Inject
MyClass(@Named("MyOtherClassA") MyInterface myOtherInterface) {
   this.myOtherInterface = myOtherInterface;
}

请引用Guice documentation了解更多详情。

关于java - 动态注入(inject) Google Guice bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58300736/

相关文章:

java - XML - XSD 的相对路径

android - 在 MVP Koin 中注入(inject) Activity 对象

java - 谷歌 Guice + 泛型 : Is there some magic behind the curtains?

java - 如何获取注入(inject)某些内容的类的类名

java - Java迭代器如何检测集合被修改而抛出ConcurrentModificationException?

java - 如何将 JSON 对象发布到 URL?

java - 列出指定类的所有常量

java - Dagger 2 子类比父类具有更具体的依赖关系

c# - IRegistrationConvention 结构图 CtorDependency

binding - 如何将字符串绑定(bind)到 Guice 中的变量?