Locked History Actions

guice/FactoryProvider/Translation

FactoryProvider(Guice 2.0 API)の抄訳

原文は、http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/assistedinject/FactoryProvider.html

呼び出し側の引数とインジェクタが供給する値をまとめてコンストラクタに与えるファクトリを供給する。

ファクトリの定義

インターフェースを作成し、そのメソッドが生成するタイプあるいはそのスーパータイプとなるようにする。メソッドの引数は生成時に必要なものとする。

public interface PaymentFactory {
   Payment create(Date startDate, Money amount);
 }

ファクトリメソッドの名前は何でもよい。createでも、 createPaymentでも、newPaymentでも。

ファクトリのパラメータを受け入れるタイプを作成する

生成される方はコンクリートな型(抽象ではない)であり、@Injectアノテーションを持つコンストラクタである。インジェクタが供給するパラメータに加え、コンストラクタはファクトリのメソッドの一致するパラメータを持つ必要がある。それぞれのファクトリ供給パラメータには@Assistedアノテーションが必要である。 これによって、これらのパラメータがモジュールにバインドされるわけではないことがドキュメント化される。

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

nullの許されるパラメータには@Nullableアノテーションが無ければならなない。

ファクトリの構成

あなたのモジュール内で、ファクトリインターフェースを(FactoryProvider.newFactoryの)返り値にバインドせよ。

bind(PaymentFactory.class).toProvider(
     FactoryProvider.newFactory(PaymentFactory.class, RealPayment.class));
  • As a side-effect of this binding, Guice will inject the factory to initialize it for use. The factory cannot be used until the injector has been initialized.

ファクトリの利用

ファクトリをあなたのアプリクラスに注入せよ。そして、そのファクトリを使用すれば、指定した引数はインジェクタで生成された値と組み合わされてインスタンスを生成する。

public class PaymentAction {
   @Inject private PaymentFactory paymentFactory;
   public void doPayment(Money amount) {
     Payment payment = paymentFactory.create(new Date(), amount);
     payment.apply();
   }
 }

パラメータタイプの区別

ファクトリメソッドのパラメータは区別されなければならない。同じ型の複数のパラメータを使いたいときは名前付の@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) {
     ...
   }
 }

値はGuiceによって作成される

返されるファクトリは子インジェクタを使って値を生成する。 この値はメソッドインターセプションを行うのに適切である。 加えて、@Injectメンバーが注入される。

@AssitedInjectを使った後方互換性

@Injectアノテーションの代わりに@AssitedInjectを使うと、制限付の後方互換モードになる。

  • Instead of matching factory method arguments to constructor parameters using their names, the

    <strong>parameters are matched by their order</strong>. The first factory method argument is used for the first @Assisted constructor parameter, etc.. Annotation names have no effect.

    Returned values are <strong>not created by Guice</strong>. These types are not eligible for method interception. They do receive post-construction member injection.