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

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

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

[翻訳]Guice User's Guide ■22. Scoping Bindings

バインディングの範囲付け

By default, Guice creates a new object for every injection. We refer to this as having "no scope." You can specify a scope when you configure a binding. For example, to inject the same instance every time:

デフォルトでは、Guiceはインジェクションのたびに新しいオブジェクトを生成します。これは「No Scope」の状態であると言えます。バインディングを設定するときに、スコープを指定することができます。たとえば、いつでも同じインスタンスをインジェクトするには以下のようにします。

bind(MySingleton.class).in(Scopes.SINGLETON);

As an alternative, you can use an annotation on your implementation class to specify the scope. Guice supports @Singleton by default:

その他代替案として、スコープを設定したい実装クラスにアノテーションを使うことも出来ます。
Guiceは、デフォルトで@Singletonアノテーションをサポートしています。

@Singleton
class MySingleton {
  ...
}

The annotation approach works with implicit bindings as well but requires that Guice create your objects. On the other hand, calling in() works with almost any binding type (binding to a single instance being an obvious exception) and overrides annotations when present. in() also accepts annotations if you don't want a compile time dependency on your scope implementation.

その上アノテーションを使う方法は、暗黙的なバインディングと一緒に動作しますが、Guiceがオブジェクトを生成することが必要です。一方、in()メソッドを呼び出すことは、ほとんどどんな型でも動作します。(一つのインスタンスにバインドすることは明らかな例外になります。)また、実行するときにはアノテーションをオーバーライドします。in()メソッドは、コンパイル時にスコープを実装した依存性を取得したくない場合は、アノテーションを受け入れます。

Specify annotations for custom scopes using Binder.bindScope(). For example, given an annotation @SessionScoped and a Scope implementation ServletScopes.SESSION:

Binder.bindScope()メソッドを使して、カスタムスコープのための特別なアノテーションを指定してください。たとえば、@SessionScopedアノテーションが与えられており、Scopeに、ServletScopes.SESSIONを実装すると場合、以下のようになります。

binder.bindScope(SessionScoped.class, ServletScopes.SESSION);