レベルエンター山本大のブログ

面白いプログラミング教育を若い人たちに

BLOCKVROCKリファレンス目次はこちら

[翻訳]Guice User's Guide ■17. Injecting Providers

インジェクティング・プロバイダー(注入仲介者)

Sometimes a client needs multiple instances of a dependency per injection. Other times a client may not want to actually retrieve an object until some time after the actual injection (if at all). For any binding of type T, rather than inject an instance of T directly, you can inject a Provider. Then call Provider.get() as necessary. For example:

クライアントが、1つのインジェクションにつき複数の依存性インスタンスを必要とする場合があります。また時には、実際のインジェクションがあったとしても、ちょっとの間オブジェクトを取得したくないという時があります。
直接Tのインスタンスを注入するためというよりも、type Tのあらゆるバインディングのため、Provider()を注入することができます。それから、必要なときにProvider.get()を呼び出すのです。以下に例を示します。

@Inject
void injectAtm(Provider<Money> atm) {
  Money one = atm.get();
  Money two = atm.get();
  ...
}

As you can see, the Provider interface couldn't get much simpler so it doesn't get in the way of easy unit testing.

お分かりの通り、Providerインターフェイスはあまりシンプルにできなかったので、簡単なユニットテストの方法がとれません。