绑定到TypeLiteral是谷歌guice中的好或坏做法

vel*_*ist 8 java dependency-injection guice

Google guice new TypeLiteral<C<T>>() {}用来克服我们无法使用的事实C<T>.class.

现在通常如下:

bind(new TypeLiteral<C<T>>() {}).to(MyCSubclassTypedToT.class);
Run Code Online (Sandbox Code Playgroud)

然而,想象一下不同的场景.我们有一个通用接口,我们想要注入,我们拥有的实现由泛型类提供.

Guice允许你这样做:

bind(new TypeLiteral<MyGenericInterface<T>>() {}).to(new TypeLiteral<MyGenericClass<T>>() {});
Run Code Online (Sandbox Code Playgroud)

另一种方法是扩展MyGenericClass,如下所示:

MyTypedClass extends MyGenericClass<T>
Run Code Online (Sandbox Code Playgroud)

然后像这样绑定它:

bind(MyGenericInterface<T>>() {}).to(MyTypedClass.class);
Run Code Online (Sandbox Code Playgroud)

如果MyGenericInterface被大量注入(尽管有不同的类型),并且每次我注入它都使用MyGenericClass,后一种方法导致过于冗长的代码.因此,我倾向于使用前者.

我非常希望听到其他人关于在guice绑定的to子句中使用TypeLiteral的意见.我担心我可能会有点短缺,因此不会看到这种方法的缺陷.

wyz*_*wyz 1

通常有两种场景:

  1. 您想要将所有实现绑定MyGenericInterfaceMyGenericClass
  2. 您想要MyGenericInterface根据其类型绑定 base的实现

对于第一个场景,bind(MyGenericInterface).to(MyGenericClass);就足够了,更简单,更容易理解。

对于第二种情况,您需要将特定类的实现绑定到特定实现,TypeLiteral 将发挥作用。

此外,您问题中的代码不清楚是T实际的类还是泛型类型。如果是泛型类型,

bind(new TypeLiteral<MyGenericInterface<T>>() {}).to(new TypeLiteral<MyGenericClass<T>>() {});

MyTypedClass extends MyGenericClass<T>

无法编译,因为未提供某些实际的类。