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

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

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

[翻訳]Guice User's Guide ■28. Static Injection

スタティックStatic変数・メソッドへのインジェクション

Static fields and methods make testing and reusing more difficult, but there are times where your only choice is to keep a static reference to the Injector.


スタティックフィールドとメソッドは、テストや再利用をより難しくします。さらに、唯一の選択肢がInjectorのスタティック参照を保持することであるなら難しさは更に倍増です。

For these situations, Guice supports injecting less accessible static members. For example, HTTP session objects often need to be serializable to support replication, but what if your session object depends on a container-scoped object? We can keep a transient reference to the object, but how do we look it up again upon deserialization?

この状況では、Guiceはより狭いアクセス範囲を持つスタティックメンバーのインジェクトをサポートします。たとえば、Http Sessionオブジェクトはレプリケーションをサポートするために、しばしばシリアライザブルにする必要があります。しかし、Sessionオブジェクトがコンテナースコープオブジェクトに依存していたとしたらどうでしょう?オブジェクトの一時的な参照を保持することは出来ます。しかし再度デシリアライズするときにはどのように検索したらよいのでしょうか?

We've found the most pragmatic solution to be static injection:

最も実用的な解決方法は、スタティックへのインジェクションです。

@SessionScoped
class User {

  @Inject
  static AuthorizationService authorizationService;
  ...
}

Guice never performs static injection automatically. You must use Binder to explicitly request that the Injector inject your static members after startup:

Guiceは、自動的にはスタティックインジェクションを行いません。起動後にInjectorがスタティックメンバーにインジェクトするように、Binderを使って明示的に要求する必要があります。

binder.requestStaticInjection(User.class);
Static injection is a necessary evil, which makes testing more difficult. If you can find a way to avoid using it, you'll probably be glad you did.

スタティックインジェクションは、必要悪です。テストをより難しくしてしまいます。回避する方法があるのであれば、そちらを採用することで幸せになれるでしょう。