Guice的辅助注入已经配置

时间:2015-04-23 12:59:01

标签: 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);
 }

接口声明如下:

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包。

为什么会出现此错误?

1 个答案:

答案 0 :(得分:40)

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

  

使参数类型不同

     

工厂方法参数的类型必须是不同的。使用   多个相同类型的参数,使用命名的@Assisted注释   消除参数的歧义。名称必须适用于   工厂方法的参数:

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

...以及具体类型的构造函数参数:

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