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

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

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

Guice User's Guide ■6. More Annotations

その他のアノテーション

When possible, Guice enables you to use annotations in lieu of explicit bindings and eliminate even more boilerplate code. Back to our example, if you need an interface to simplify unit testing but you don't care about compile time dependencies, you can point to a default implementation directly from your interface.

できれば、Guiceは明示的な結合の代わりにアノテーションを使用して、さらに多くの配管コードを排除できるようにします。先ほどのサンプルに戻ってみます。もしも、ユニットテストのためにインターフェイスをシンプルに保っておく必要があり、しかしコンパイル時に依存性を意識しないようにするならば、インターフェイスに直接デフォルトの実装クラスを指定しておくことが出来ます。

@ImplementedBy(ServiceImpl.class)
public interface Service {
  void go();
}

If a client needs a Service and Guice can't find an explicit binding, Guice will inject an instance of ServiceImpl.

クライアントがServiceを必要とするときや、Guiceが明示的にbindされたオブジェクトを見つけられないとき、Guiceは、ServiceImplクラスのインスタンスをインジェクトします。

By default, Guice injects a new instance every time. If you want to specify a different scope, you can annotate the implementation class, too.

デフォルトでは、Guiceは常に新しいインスタンスを注入します。もし、異なるスコープを記述したい場合、実装クラスをアノテーションで注釈することもできます。

@Singleton
public class ServiceImpl implements Service {
  public void go() {
    ...
  }
}