简体   繁体   English

使用Guice多次绑定到同一提供者实例

[英]Multiple bindings to the same provider instance with Guice

I have two interfaces A and B and B is extending A. 我有两个接口A和B,而B正在扩展A。

I have one provider being able to provide instances whose Class is implementing B (and consequently A). 我有一个提供程序,可以提供其类正在实现B(因此实现A)的实例。

I would like to bind Provider to B.class (straightforward) and to A.class with an Annotation in a singleton scope. 我想在单例范围内将Provider绑定到B.class(直接)和带有注释的A.class。

bind(B.class).toProvider(MyBImplProvider.class).in(Scopes.SINGLETON);
bind(A.class).annotatedWith(Names.named("B")).toProvider(MyBImplProvider.class).in(Scopes.SINGLETON);

How to return the same instance from the provider no matter if I inject through B.class or through A.class+Annotation. 无论我是通过B.class还是通过A.class + Annotation注入的,如何从提供者返回相同的实例。 For instance, I'd like to be able to define constuctors as 例如,我希望能够将构造函数定义为

@Inject
C(B param)

or 要么

@Inject
C(@Named("B") param)

In both case, I'd like param to be valuated with the same singleton. 在这两种情况下,我都希望对param进行相同的单例评估。

How about making your A Provider depend on the B provider you've defined above? 如何使您的A提供者取决于您在上面定义的B提供者?

@Provides 
@Named("B")
A provideA(Provider<B> bProvider) {
  return bProvider.get();
}

That should work since you said B extends A. You might need to play around with the @Named bit. 这应该起作用,因为您说过B扩展了A。您可能需要使用@Named位。

Another option would be to use a toInstance(yourObject) binding. 另一种选择是使用toInstance(yourObject)绑定。 But this makes it messy to inject any dependencies into that object. 但这使将任何依赖项注入该对象变得混乱。 You would have to use Binder#requestInjection() . 您将必须使用Binder#requestInjection()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM