如何创建2个类实例注入不同类的依赖项实现(通过guice)?

我有一个名为“Consumer”的界面 .

实现如下:

public class ConsumerImpl  implements Consumer {
  DBManager  m_dbm ;
  @Inject
  public ConsumerImpl  (DBManager dbm) {
    m_dbm = sdbm;       
  }

}

我需要有2个consumerImpl类的实例,但是注入了不同的DBManager实现 . 如何通过guice配置?

回答(1)

2 years ago

像这样的东西?

public class GuiceDependencyExample {

  static class DBManager {}
  static class DBManagerVendor1 extends DBManager {}
  static class DBManagerVendor2 extends DBManager {}
  static interface Consumer {
    DBManager getDbManager();
  }

  static @Retention(RetentionPolicy.RUNTIME) @BindingAnnotation @interface DBManager1 {}
  static @Retention(RetentionPolicy.RUNTIME) @BindingAnnotation @interface DBManager2 {}

  static class ConsumerImpl  implements Consumer {
    DBManager  m_dbm;
    @Inject
    public ConsumerImpl  (DBManager dbm) { m_dbm = dbm; }

    public DBManager getDbManager() { return m_dbm; }
  }

  static abstract class ConsumerModule extends PrivateModule {
    private final Class<? extends Annotation> annotation;

    ConsumerModule(Class<? extends Annotation> annotation) {
      this.annotation = annotation;
    }

    @Override 
    protected void configure() {
      bind(Consumer.class).annotatedWith(annotation).to(ConsumerImpl.class);
      expose(Consumer.class).annotatedWith(annotation);
      bindDbManager();
    }

    abstract void bindDbManager();
  }

  static class Client {
    @DBManager1
    @Inject
    Consumer consumer1;

    @DBManager2
    @Inject
    Consumer consumer2;
  }

  @Test
  public void test() {
    Injector i = Guice.createInjector(
        new ConsumerModule(DBManager1.class) {
          @Override void bindDbManager() {
            bind(DBManager.class).toInstance(new DBManagerVendor1());
          }
        },
        new ConsumerModule(DBManager2.class) {
          @Override void bindDbManager() {
            bind(DBManager.class).toInstance(new DBManagerVendor2());
          }
        });
    Client client = i.getInstance(Client.class);
    assertTrue(client.consumer1.getDbManager() instanceof DBManagerVendor1);
    assertTrue(client.consumer2.getDbManager() instanceof DBManagerVendor2);
  }