16

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 バンドルを使用しています。

なぜこのエラーが発生するのですか?

4

1 に答える 1

51

これは一般的な問題です。解決策は 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) {
     ...
  }    }
于 2015-04-24T19:06:02.467 に答える