java - Guice 辅助注入(inject)已配置

标签 java dependency-injection guice assisted-inject

我对 AssistedInject 有疑问。我按照此链接上的说明进行操作 https://github.com/google/guice/wiki/AssistedInject 但是当我运行我的应用程序时出现错误:

ERROR [2015-04-23 14:49:34,701] com.hubspot.dropwizard.guice.GuiceBundle: Exception occurred when creating Guice Injector - exiting
! com.google.inject.CreationException: Unable to create injector, see the following errors:
!
! 1) A binding to java.lang.String annotated with @com.google.inject.assistedinject.Assisted(value=) was already configured at com.demo.migrator.service.democlient.DemoAPIFactory.create().
!   at com.demo.migrator.service.democlient.DemoAPIFactory.create(DemoAPIFactory.java:1)
!   at com.google.inject.assistedinject.FactoryProvider2.initialize(FactoryProvider2.java:577)
!   at com.google.inject.assistedinject.FactoryModuleBuilder$1.configure(FactoryModuleBuilder.java:335) (via modules: com.demo.migrator.MigrationModule -> com.google.inject.assistedinject.FactoryModuleBuilder$1)

这是我的模块配置:

install(new FactoryModuleBuilder()
    .implement(DemoAPI.class, DemoClient.class)
    .build(DemoAPIFactory.class));

这是我的工厂的样子:

 public interface DemoAPIFactory {
   DemoAPI create(String _apiKey, String _secretKey);
 }

接口(interface)声明如下:

public interface DemoAPI {
   //list of interface methods
}

下面是实现

 @Inject
public DemoClient(@Assisted String _apiKey, 
       @Assisted String _secretKey) {
    secretKey = _secretKey;
    apiKey = _apiKey;
    baseURL = "xxxxx";
    expirationWindow = 15;
    roundUpTime = 300;
    base64Encoder = new Base64();
    contentType = "application/json";
}

我正在使用 dropwizard guice 包。

为什么会出现这个错误?

最佳答案

这是一个常见问题,解决方案记录在 javadoc 中:

Making parameter types distinct

The types of the factory method's parameters must be distinct. To use multiple parameters of the same type, use a named @Assisted annotation to disambiguate the parameters. The names must be applied to the factory method's parameters:

 public interface PaymentFactory {
    Payment create(
        @Assisted("startDate") Date startDate,
        @Assisted("dueDate") Date dueDate,
        Money amount);    } 

...and to the concrete type's constructor parameters:

public class RealPayment implements Payment {
  @Inject
  public RealPayment(
     CreditService creditService,
     AuthService authService,
     @Assisted("startDate") Date startDate,
     @Assisted("dueDate") Date dueDate,
     @Assisted Money amount) {
     ...
  }    }

关于java - Guice 辅助注入(inject)已配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29824177/

相关文章:

c# - 使用简单注入(inject)器解析通用装饰器

c# - .NET Core 依赖注入(inject),解析泛型接口(interface)

java - Play Framework 2.4 - 注入(inject)的字段始终为空

JavaFX8 - 使用 Guice 的线程任务

java - Java中使用Scanner读取整行字符串

java - 如何隐藏手/光标?

java - jTextArea 上的查找/替换对话框

java - 在 '@'之前屏蔽电子邮件中的中间字符

c# - 如何使用 Microsoft.Extensions.DependencyInjection 在 .net 框架中的 webapi 中注入(inject)依赖项?

java - Guice @Inject 无法使用多个构造函数注入(inject)