Dependency injection 绑定类<&燃气轮机;带着Guice

Dependency injection 绑定类<&燃气轮机;带着Guice,dependency-injection,guice,Dependency Injection,Guice,我有一个不同类的实例列表,我只想将它们绑定到自己的类。 我尝试使用binder.bind(obj.getClass()).toInstance(obj)对每个循环进行编译,但这当然不会编译,因为编译器无法解析泛型T。 还有什么方法可以实现呢?这里您只需要对原始类型进行转换。正如在下面的评论(谢谢!)中所述,Guice实际上就像一个从键(通常是类对象)到值(该类的提供者)的映射,泛型只是帮助保持公共用例的正常。如果您确定密钥匹配,则可以如下所示覆盖泛型: @Override protected v

我有一个不同类的实例列表,我只想将它们绑定到自己的类。 我尝试使用
binder.bind(obj.getClass()).toInstance(obj)
对每个循环进行编译,但这当然不会编译,因为编译器无法解析泛型T。
还有什么方法可以实现呢?

这里您只需要对原始类型进行转换。正如在下面的评论(谢谢!)中所述,Guice实际上就像一个从键(通常是类对象)到值(该类的提供者)的映射,泛型只是帮助保持公共用例的正常。如果您确定密钥匹配,则可以如下所示覆盖泛型:

@Override
protected void configure() {
  for (Object object : getYourListOfInitializedObjects()) {
    bindObjectAsSingleton(object);
  }
}

/** Suppress warnings to convince the Java compiler to allow the cast. */
@SuppressWarnings({"unchecked", "rawtypes"})
private void bindObjectAsSingleton(Object object) {
  bind((Class) object.getClass()).toInstance(object);
}
如上所述,这并不鼓励良好的Guice设计,因为即使您有
DependencyImpl
实现
DependencyImpl
,上述操作也只会创建到
DependencyImpl
的绑定。此外,必须创建初始化单例列表中的所有类,而不使用Guice注入本身,因此您将自己限制为在没有Guice帮助的情况下外部初始化的类。如果要从遗留的“一堆单例”迁移到Guice,您可能会使用上述模式,但如果您尽快像这样构造
configure
方法,您可能会走得更远:

@Override
public void configure() {
  // Let Guice create DependencyOne once, with injection,
  // immediately on injector creation.
  bind(DependencyOne.class).asEagerSingleton();

  // Let Guice create DependencyTwo once, with injection,
  // but this way you can hopefully rely on interface DependencyTwo
  // rather than concrete implementation DependencyTwoImpl.
  bind(DependencyTwo.class).to(DependencyTwoImpl.class).asEagerSingleton();

  // Bind DependencyThree to an instance. Instance bindings are
  // implicitly singletons, because you haven't told Guice how to
  // create another one.
  bind(DependencyThree.class).toInstance(getDependencyThreeInstance());

  // ...and so forth for everything in your list.
}

很可能你做错了事情。如果实例列表是静态已知的,那么应该为每个类执行多个
bind().toInstance()
调用。如果事先不知道这个列表,那么您应该重新考虑您的设计。Guice不应该这样使用。调查一下,也许这就是你需要的。这是一个很好的答案。为OP添加一点值——如果您阅读了guice如何使用键值存储内部绑定,那么这可能会让您更清楚地了解如何使用泛型。我知道我的代码(使用了很多参数化类型/方法等)在进行概念转换时遇到了问题,最终理解了实际的绑定机制,使解决涉及泛型和使用类型文本之类的问题变得更加清晰。