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

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

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

[翻訳]Guice User's Guide ■29. Optional Injection

省略可能なインジェクション

Sometimes your code should work whether a binding exists or not. In these cases, you can use @Inject(optional=true) and Guice can override your default implementation with a bound implementation when available. For example:

バインディングがあろうがなかろうが構わずプログラムが動かなくてはならないときがあります。このような状況では、@Inject(optional=true)を使ってください。するとGuiceは、バインドされた実装が利用可能なら、それを使ってデフォルトの実装をオーバーライドすることができます。

@Inject(optional=true) Formatter formatter = new DefaultFormatter();

If someone creates a binding for Formatter, Guice will inject an instance from that binding. Otherwise, assuming Formatter isn't injectable itself (see Implicit Bindings), Guice will skip the optional member.

誰かがFormatterのバインディングを生成すると、Guiceはそのバインディングからインスタンスをインジェクトします。しかしながら、傲慢なFormatterは、インジェクト可能ではありません(「16.Implicit Binding」のセクションを参照)。Guiceは省略可能なメンバーをスキップします。

Optional injection applies only to fields and methods, not constructors. In the case of methods, if a binding for one parameter is missing, Guice won't inject the method at all, even if bindings to other parameters are available.

省略可能なインジェクションは、フィールドとメソッドだけに適用できます。コンストラクタには適用出来ません。メソッドの場合、1つのパラメーターが欠如しているとしたら、他のパラメーターへのバインドが有効だったとしてもGuiceはすべてのメソッドにインジェクトしません。