我最近遇到一些代碼,它使用同一方法上的@Provides
和@Inject
註解。該方法有兩個非原始參數和一個非void返回類型。合併@Provides和@Inject
我想知道是否合理使用這兩個串聯。從我可以收集/推測的內容來看,似乎使用@Inject
來構建使用Guice的方法依賴關係,而使用@Provides
來綁定返回類型。任何想法,將不勝感激。
我最近遇到一些代碼,它使用同一方法上的@Provides
和@Inject
註解。該方法有兩個非原始參數和一個非void返回類型。合併@Provides和@Inject
我想知道是否合理使用這兩個串聯。從我可以收集/推測的內容來看,似乎使用@Inject
來構建使用Guice的方法依賴關係,而使用@Provides
來綁定返回類型。任何想法,將不勝感激。
不,不會有這種情況,您可以用同樣的方法看到@Provides
和@Inject
。
@Inject
使得上構造函數,方法和字段感:
void
。例如:
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
具有窄得多的目的:當在吉斯模塊中使用,@Provides
推移方法和指示吉斯應該調用該方法時,它需要該方法的一個實例可能 - 參數化類型(並從方法本身繼承綁定註釋或限定符)。 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
方法被調用一次以存儲依賴關係,並且每當需要新實例時應調用@Provides
方法。
非常感謝您的澄清。因此,爲了清楚起見,用@Inject註解的方法在構造YourInjectableClass之後調用,然後調用? – OrangeApple3
@ OrangeApple3是的。該技術被稱爲[方法注入](https://github.com/google/guice/wiki/Injections#method-injection)。 –