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

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

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

Guice User's Guide ■8. Startup

起動時

You configure Guice by implementing Module. You pass Guice a module, Guice passes your module a Binder, and your module uses the binder to configure bindings. A binding most commonly consists of a mapping between an interface and a concrete implementation. For example:

モジュールの実装によって、Guiceを設定します。Guiceにモジュールを引き渡します。Gujceは、モジュールをBinderに渡します。そしてモジュールは、設定を結びつけるためにBinderを使います。
最も一般的なバインディングは、インターフェイスと具体的な実装の間のマッピングで成りたっています。
たとえば以下です:

public class MyModule implements Module {
  public void configure(Binder binder) {
    // Bind Foo to FooImpl. Guice will create a new
    // instance of FooImpl for every injection.
    binder.bind(Foo.class).to(FooImpl.class);

    // Bind Bar to an instance of Bar.
    Bar bar = new Bar();
    binder.bind(Bar.class).toInstance(bar);
  }
}

Guice can look at the classes you tell it about during this stage and any classes those classes know about, and tell you whether or not you're missing any dependencies. For example, in a Struts 2 application, Guice knows about all of your actions. Guice can validate your actions and anything they transitively depend on, and fail early if necessary.

Guiceは、このステージの間に指定されたクラスとそれらのクラスが知っているすべてのクラスを見ることが出来ます。そして、依存性が欠如していないかどうかを知らせてくれます。たとえば、Struts 2のアプリケーションでは、GuiceはユーザーがつくったすべてのActionクラスについて知っています。Guiceは、ユーザーがつくったActionと、他動的に依存するすべてのクラスを検証します。そして必要に応じて早期にエラーを返して起動を中止します。

Creating an Injector entails the following steps:

Injectorの作成には以下のステップがあります。

  1. First, create an instance of your module and pass it to Guice.createInjector().
  2. Guice creates a Binder and passes it to your module.
  3. Your module uses the binder to define bindings.
  4. Based on the bindings you specified, Guice creates an Injector and returns it to you.
  5. You use the injector to inject an object.

  1. まず、モジュールのインスタンスを生成します。そしてそれをGuiceのcreateInjector()メソッドに引き渡します。
  2. Guiceは、Binderオブジェクトを生成し、それに対してモジュールを引き渡します。
  3. モジュールは、Binderオブジェクトを使って結合を定義します。
  4. 指定されたバインドに基づいて、GuiceはInjectorを生成し開発者にそれを返します。
  5. 開発者は、Injectorを使ってオブジェクトを注入します。