【问题标题】:Google Guice - Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not privateGoogle Guice - 类必须有一个(且只有一个)用@Inject 注释的构造函数或一个非私有的零参数构造函数
【发布时间】:2020-04-27 06:07:01
【问题描述】:

全部

我有一些关于 Google Guice 的问题。任何帮助表示赞赏。

我有一个处理程序接口和它的实现。

public interface Handler {
   void handle();
}
public class HandlerImpl implements Handler {
   private Filter filterOne;

   @Override
   void handler() {
     filterOne.foo();
   }
}

过滤器是另一个接口:

public interface Filter {
   void foo();
}

它有多种实现方式。

public class FilterOne implements Filter {
   void foo() {
   }
}

public class FilterTwo implements Filter {
   void foo() {
   }
}

然后在我的 Guice 模块中:

public class HandlerModule extends AbstractModel {

  @Override
  protected void configure() {
     bind(Handler.class).to(HandlerImpl.class);
  }

  @Provides
  @Singleton
  public Handler provideHandler(@Named("filterOne")filter filterOne) {
    return new HandlerImpl(filterOne);
  }

  @Provides
  @Singleton
  @Named("filterOne")
  public Filter provideFilterOne() {
    return new FilterOne();
  }

  @Provides
  @Singleton
  @Named("filterTwo")
  public Filter provideFilterTwo() {
    return new FilterTwo();
  }
}

使用上述实现,我总是收到错误 - 在 HandlerImpl 中找不到合适的构造函数。类必须有一个(且只有一个)用@Inject 注释的构造函数或一个非私有的零参数构造函数。

我使用@Named 来区分两个过滤器。我用错了吗? 是不是因为我有两个 Filter 实现,而 Guice 在尝试提供 HandlerImpl 时无法判断使用哪一个?

【问题讨论】:

  • "是不是因为我有两个 Filter 实现,而 Guice 在尝试提供 HandlerImpl 时无法判断使用哪一个?"确切地。那么你想用哪一个呢?或者你想如何决定使用哪一个?
  • 我更新了问题。对于每个过滤器,我都有一个 @Named 注释。然后在处理程序中,我用它来表示我要使用的过滤器工厂。我用错了吗?

标签: java guice


【解决方案1】:

您绑定Handler.class 两次:

  • configure() 方法中:bind(Handler.class).to(HandlerImpl.class);
  • 作为提供商:
  @Singleton
  public Handler provideHandler(@Named("filterOne")filter filterOne) {
    return new HandlerImpl(filterOne);
  }

第一个绑定不起作用,因为HandlerImpl 没有使用@Inject 注释的构造函数。如果你修复它,它仍然无法工作 - 你不能为同一个键提供多个绑定。

TL;DR:从 configure() 方法中删除 bind(Handler.class).to(HandlerImpl.class);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多