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

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

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

Guice User's Guide ■4. Dependency Injection with Guice

Guiceを使ったDependency Injection(依存性の注入)

Writing factories and dependency injection logic by hand for every service and client can become tedious. Some other dependency injection frameworks even require you to explicitly map services to the places where you want them injected.

ファクトリーや依存性を注入するロジックを手作業ですべてのサービスとクライアントにたいして記述していると飽きてしまいます。Guiceではない他のDIフレームワークは、サービスをどこに注入したいのかを明示的に対応付けることを求めます。

Guice aims to eliminate all of this boilerplate without sacrificing maintainability.

Guiceは、メンテナンス性を犠牲にせずにこういったすべての配管的コードを駆逐することを目標としています。

With Guice, you implement modules. Guice passes a binder to your module, and your module uses the binder to map interfaces to implementations. The following module tells Guice to map Service to ServiceImpl in singleton scope:

Guiceを使うには、moduleを実装することからはじめます。GuiceはBinderというオブジェクトを返します。モジュールでそのバインダーを使ってインターフェイスと実装を結び付けます。次に示すモジュールは、Guiceに、ServiceImplをServiceにシングルトンスコープで結び付けることを伝えます。

public class MyModule extends AbstractModule {
  protected void configure() {
    bind(Service.class)
      .to(ServiceImpl.class)
      .in(Scopes.SINGLETON);
  }
}

A module tells Guice what we want to inject. Now, how do we tell Guice where we want it injected? With Guice, you annotate constructors, methods and fields with @Inject.

Moduleは何を注入したいかをGuiceに伝えます。さて、では「どこに注入したいか?」については、どうやってGuiceに伝えることができるのでしょう?それは、@Injectアノテーションをつかいます。これはコンストラクタや、メソッドやフィールドに使うことが出来ます。

public class Client {

  private final Service service;

  @Inject
  public Client(Service service) {
    this.service = service;
  }

  public void go() {
    service.go();
  }
}

The @Inject annotation makes it clear to a programmer editing your class which members are injected.

@Injectアノテーションは、どのメンバ変数がインジェクトされるかをあなたのクラスを変数しているプログラマにわかるようにします。

For Guice to inject Client, we must either directly ask Guice to create a Client instance for us, or some other class must have Client injected into it.

GuiceがClientに注入するためには、Clientインスタンスを作成するように直接Guiceに頼まなければなりません、またはある他のクラスはClientをそれに注入させなければなりません。