dependency-injection - 使用 Guice 绑定(bind)类 <?>

标签 dependency-injection guice

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

最佳答案

这里您只需要转换为原始类型。如 chooks下面的评论(谢谢!),Guice 有效地充当从键(通常是类对象)到值(该类的提供者)的映射,而泛型只是帮助保持常见情况的理智。如果您确定您的 key 匹配,您可以像这样覆盖泛型:

@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);
}

作为Vladimir上面提到,这往往不鼓励好的 Guice 设计,因为即使你有你的 DependencyImpl 实现 Dependency,上面只会创建到 DependencyImpl。此外,初始化单例列表中的所有类都必须在没有 Guice 注入(inject)的情况下创建,因此您将自己限制在没有 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.
}

关于dependency-injection - 使用 Guice 绑定(bind)类 <?>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20634568/

相关文章:

java - 根据参数重用Guice中的Provide

go - 在 Go Wire 注入(inject)中使用单例模式

spring - AnnotatedElementUtils错误 Spring 测试

java - 选择在运行时 spring 注入(inject)哪个实现

java - 在其模块中访问 Guice 注入(inject)器?

parameter-passing - 使用 Google Guice 注入(inject)构造函数参数值

Spring : Injecting the object that launches the ApplicationContext into the ApplicationContext

java - Guice:请求实例,而不是类型

java - 在运行时使用注释获取 guice 对象?

java - Guice - 如何让多个模块为一件事做出贡献?