简体   繁体   中英

Multiple bindings to the same provider instance with Guice

I have two interfaces A and B and B is extending A.

I have one provider being able to provide instances whose Class is implementing B (and consequently A).

I would like to bind Provider to B.class (straightforward) and to A.class with an Annotation in a singleton scope.

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. 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.

How about making your A Provider depend on the B provider you've defined above?

@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.

Another option would be to use a toInstance(yourObject) binding. But this makes it messy to inject any dependencies into that object. You would have to use Binder#requestInjection() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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