いいえ、同じ方法で@Provides
と@Inject
が表示される場合はありません。
@Inject
がコンストラクタ、メソッド、およびフィールドに理にかなって:コンストラクタで
- 、それはDIフレームワークを呼び出す必要がコンストラクタをマーク。フレームワークはすべてのパラメータ値を提供します。
- フィールドでは、DIフレームワークがフィールドを外部から設定する必要があることを示します。フレームワークはフィールド値を提供します。
- メソッドでは、構築後にDIフレームワークがメソッドを正確に1回呼び出す必要があることを示します。フレームワークはパラメータ値を提供します。戻り値は意味がなく、しばしば
void
です。例えば
:Guiceのモジュールで使用される場合、@Provides
はメソッドに行くと、それはおそらくメソッドのインスタンスを必要とするたびにGuiceのメソッドを呼び出す必要があることを示し:
public class YourInjectableClass {
// Guice will use this constructor...
@Inject public YourInjectableClass(YourDep dep) { /* ... */ }
// ...instead of this one
public YourInjectableClass(YourDep dep, YourOtherDep otherDep) { /* ... */ }
// Guice will populate this field after construction.
@Inject YourField yourField;
@Inject public void register(Registry registry) {
// Guice will create or get a Registry and call this method after construction.
// It sometimes makes sense for this to be protected or package-private,
// so this class's consumers aren't tempted to call it themselves.
}
}
@Provides
は非常に狭い目的を有しています-parameterized型(およびメソッド自体からバインディング注釈や修飾子を継承します)。 Daggerには、@Provides
がJSR-330依存性注入標準で定義されていないため、同様のアノテーションがあります。
public class YourModule extends AbstractModule {
@Override public void configure() {) // still needed for AbstractModule
// Guice will call this whenever it needs a @SomeBindingAnnotation YourInstance.
// Because you list a YourDep as a parameter, Guice will get and pass in a YourDep.
@Provides @SomeBindingAnnotation YourInstance create(YourDep dep) {
return YourInstanceFactory.create(dep);
}
}
その結果、あなたは、同じ方法ではおろか、同じファイルでこれらの注釈を参照してくださいことはほとんどないはずです。唯一の例外は、それ自体が注入可能なモジュールを作成する疑わしい習慣(おそらく、異なるインジェクタを構成するためにあるインジェクタから注入されたモジュールを取得する)を実行した場合でも、同じ方法でそれらを表示しない場合です。 @Inject
メソッドは依存関係を格納するために1回呼び出され、新しいインスタンスが必要なときはいつでも@Provides
メソッドを呼び出す必要があります。
ありがとうございます。ですから、@Injectでアノテーションされたメソッドは、YourInjectableClassの構築後に呼び出されます。 – OrangeApple3
@ OrangeApple3はい。この手法は[メソッドインジェクション](https://github.com/google/guice/wiki/Injections#method-injection)と呼ばれています。 –