Guice绑定绑定了子类吗?(Does Guice binding bind subclass as well?)

编程入门 行业动态 更新时间:2024-10-09 04:18:11
Guice绑定绑定了子类吗?(Does Guice binding bind subclass as well?)

所以我有一个模块,它将一个接口与一个实现类绑定在一起。

bind(ILocalStore.class).to(LocalStore.class);

这个绑定是否会注入下面的构造函数:

@Inject public LocalStoreUser(LocalStore localstore) { this.localstore = localstore }

So I have a module which binds an Interface with an implementation class.

bind(ILocalStore.class).to(LocalStore.class);

Will this binding also inject the following constructor:

@Inject public LocalStoreUser(LocalStore localstore) { this.localstore = localstore }

最满意答案

注射会起作用,但不是因为绑定。

Guice将查找视为简单的Map<Key, Provider>查找,其中Key由(绑定注释,参数化类型)对组成。 Guice不会自动遍历类型层次结构,或者修改查找键(例如,检查未注释或原始类型的绑定)。

然而,如果LocalStore有一个公共的无参数构造函数,Guice可以直接创建类型,所以上面的代码将会工作 - 它与自动绑定子类无关。


考虑下面的例子:

interface A {} interface B extends A {} public class C implements B {}

根本没有任何绑定,你可以注入C,因为它有一个隐含的公共无参数构造函数。 要求注射A或B将失败。

如果你要bind(A.class).to(C.class)你可以注入A(显式)或C(隐式)而不是B. Guice也不会绑定子接口,所以B没有实现。

超类/超接口也是如此:如果要bind(B.class).to(C.class) ,则可以注入B(显式)或C(隐式),但不能注入A,即使B扩展A.

如果你要bind(A.class).to(B.class) bind(B.class).to(C.class) ,那么你可以注入A,B或C而不用重复自己。

The injection will work, but not because of the binding.

Guice treats lookups as if they were a simple Map<Key, Provider> lookup, where Key is composed of a (binding annotation, parameterized type) pair. Guice will not automatically walk up the type hierarchy for you, or otherwise modify the lookup key (checking for a non-annotated or raw type binding, for instance).

However, if LocalStore has a public no-argument constructor (or an @Inject-annotated constructor as you've listed), Guice can create the type directly, so the code above will work—it just has nothing to do with binding subclasses automatically.


Consider the following example:

interface A {} interface B extends A {} public class C implements B {}

Without any bindings at all, you could inject C, because it has an implicit public no-arg constructor. The same would apply if C has an @Inject-annotated constructor. Requesting injection of A or B will fail.

If you were to bind(A.class).to(C.class) you could inject A (explicit) or C (implicit) but not B. Guice will not bind the subinterface as well, so B has no implementation.

Same goes for superclasses/superinterfaces: If you were to bind(B.class).to(C.class) you could inject B (explicit) or C (implicit) but not A, even though B extends A.

If you were to bind(A.class).to(B.class) and bind(B.class).to(C.class), then you could inject A, B, or C without repeating yourself.

更多推荐

本文发布于:2023-08-03 22:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1400899.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子类   定了   绑定   Guice   bind

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!