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

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

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

[翻訳]Guice User's Guide ■16. Implicit Bindings

暗黙的なバインド

As we saw in the introduction, you don't always have to declare bindings explicitly. In the absence of an explicit binding, Guice will try to inject and create a new instance of the class you depend on. If you depend on an interface, Guice will look for an @ImplementedBy annotation which points to the concrete implementation. Take the following explicit binding to a concrete, injectable class named Concrete for example. It basically says, bind Concrete to Concrete. That's explicit, but also a little redundant.

序論で見たように、いつも明示的にバインディングを宣言する必要はありません。 明示的なバインディングがないとき、Guiceは依存するクラスの新しいインスタンスを作成して注入しようとします。インターフェイスに依存させる場合、Guiceは具体的な実装を示す@ImplementedByアノテーションを探します。以下の明示的な具象クラス(たとえば、Concreteという名前の注入可能な具象クラス)へのバインディングを行ってください。それは基本的に言って、ConcreteからConcreteへのバインドです。 これはとても明示的です。しかし少々余分だともいえます。

bind(Concrete.class);

Removing the binding above would not affect the behavior of this class:

上記のバインディングを取り除いても、このクラスの振舞いに影響しません。

class Mixer {

  @Inject
  Mixer(Concrete concrete) {
    ...
  }
}

So, take your pick: explicit or brief. In the event of an error, Guice will produce helpful messages either way.

したがって、「明白さ」または「簡潔さ」のどちから好きなほうを選んでください。エラーイベントでは、Guiceはいずれにせよ有用なメッセージを出します。