我正在将构造函数 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;
}
}
}
我需要能够在运行时实例化一个
MyClass
与 MyOtherClassA
或 MyOtherClassB
实例。
所以在一个代码路径中我需要类似的东西:
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/