これを見ると、Providerの使いどころの1つがハッキリ分かってきます。 * 勝手にinjectできないクラス(この例だとServiceを直接@InjectできないWidgetクラス)のプロキシとなり、 * そのクラスの依存性を解決した上でGuiceから使えるようにする という役割です。
http://d.hatena.ne.jp/arumani/20070321/1174499543
http://groups.google.com/group/google-guice/browse_thread/thread/0fa19067dd52559d
http://d.hatena.ne.jp/arumani/20070602/1180809705
Injectorそのものをinit()でinjectする。
サンプルの最後のGuiceSample6.javaが参考になった。
http://gihyo.jp/dev/serial/01/awdp/000102?page=2
Your code should deal directly with the Injector as little as possible. Instead, you want to bootstrap your application by injecting one root object. The container can further inject dependencies into the root object's dependencies, and so on recursively. In the end, your application should ideally have one class (if that many) which knows about the Injector, and every other class should expect to have dependencies injected.
出来るだけ、開発者のコードが直接Injectorを扱うことは避けるべきです。その代わりに、アプリケーションを独力で動かしたいのなら、一つのルートオブジェクトに注入してください。コンテナは、ルートオブジェクトの依存オブジェクトにさらに依存性を注入し、、というようにして再帰的に依存性を注入します。結局、アプリケーションは、1つのクラス(もしかしたらたくさんかもしれませんが)だけがInjectorを知っていることが理想です。そして他のあらゆるクラスが依存性を注入されるようにすべきです。
For example, a web application framework such as Struts 2 bootstraps your application by injecting all of your actions. You might bootstrap a web service framework by injecting your service implementation classes.
例えば、Struts 2のようなWebアプリケーションフレームワークでは、すべてのActionをインジェクトすることによって、アプリケーションが独力で動作するようになります。サービスを実装したクラスを注入することによって、Webサービスフレームワークを独力で動作させるようにもできるでしょう。
Dependency injection is viral. If you're refactoring an existing code base with a lot of static methods, you may start to feel like you're pulling a never-ending thread. This is a Good Thing. It means dependency injection is making your code more flexible and testable.
Dependency Injectionは、ウィルスです。既存のコードベースを、多くのスタティックメソッドによってリファクタリングしているならば、果てしない糸を引いている気がし始めるでしょう。これはよい事なのです。それが意味するのは、Dependency Injectionが開発者のコードをより柔軟に、テストしやすくしているといいうことなのです。
If you get in over your head, rather than try to refactor an entire code base all in one shot, you might temporarily store a reference to the Injector in a static field somewhere or use static injection. Name the field's class clearly though: InjectorHack? and GodKillsAKittenEveryTimeYouUseMe? come to mind. Keep in mind that you you'll have to mock this class, and your unit tests will have to install an Injector here by hand, and remember to clean up afterwards.
一撃で全体のコードベースをリファクタリングすることを試みるより、むしろ考えられるのは、どこかのスタティックフィールドに一時的にInjectorの参照を格納するか、スタティックインジェクションを使うことかもしれません。もっともその場合は、明確にフィールドのクラスを命名してください: InjectorHack?やGodKillsAKittenEveryTimeYouUseMe?()が思い浮かびます。 モックにもこのクラスを保持しなくてはならないことを忘れないでください。ユニットテストでは手作業でInjectorをここにインストールし、後で、削除することを忘れないようにしてください。
↓のサイトを参考にしてもう少し分かり易くしてみた。
http://d.hatena.ne.jp/iad_otomamay/20070318/1174185598