简体   繁体   中英

With Guice, how to provide different instances of the same Type?

I have types A and B. I would like to bind two instances of Type A, and provide two instances of Type B - with instances of Type B being created based on an instance of Type A.

I attempt to do this below, but the call to providesB2() results in this exception:

A binding to javax.sql.DataSource was already configured at ...providesB1()

I imagine an easy solution to this is not to provide two instances of Type B, rather to have my provider methods return Types C and D, both of which extend B. But is there a way to accomplish this while providing two instances of Type B?

@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@interface A1 {}

@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@interface A2 {}

//....

(A.class).annotatedWith(A1.class).toInstance(aInstance1);
(A.class).annotatedWith(A2.class).toInstance(aInstance2);

@Provides
@Singleton
@Inject
B providesB1(@A1 a) {
  return new B(a)
}

@Provides
@Singleton
@Inject
B providesB2(@A2 a) {
  return new B(a)
}

You already distinguished the two different A's with binding annotations @A1 and @A2 . You just need to distinguish the two different B's with binding annotations as well, by adding whatever your annotation is to the list of annotations for providesB1 and providesB2 .

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