我正在将构造函数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
我该怎么做?
有两种方法可以实现这一点
- 绑定批注
创建以下批注类
public class Annotations {
@BindingAnnotation
@Target({FIELD, PARAMETER, METHOD})
@Retention(RUNTIME)
public @interface ClassA {}
@BindingAnnotation
@Target({FIELD, PARAMETER, METHOD})
@Retention(RUNTIME)
public @interface ClassB {}
}
在模块类中添加绑定
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(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 文档。