2017-06-17 64 views
1

我最近遇到一些代碼,它使用同一方法上的@Provides@Inject註解。該方法有兩個非原始參數和一個非void返回類型。合併@Provides和@Inject

我想知道是否合理使用這兩個串聯。從我可以收集/推測的內容來看,似乎使用@Inject來構建使用Guice的方法依賴關係,而使用@Provides來綁定返回類型。任何想法,將不勝感激。

回答

6

不,不會有這種情況,您可以用同樣的方法看到@Provides@Inject

@Inject使得上構造函數,方法和字段感:

  • 在構造函數,它標誌着該DI框架應該調用構造函數。該框架提供了所有參數值。
  • 在字段上,它表示DI框架應該從外部設置字段。該框架提供了字段值。
  • 在方法上,它表明在構建之後,DI框架應該調用方法,恰好一次是。該框架提供參數值。返回值沒有意義,通常爲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方法。

+0

非常感謝您的澄清。因此,爲了清楚起見,用@Inject註解的方法在構造YourInjectableClass之後調用,然後調用? – OrangeApple3

+0

@ OrangeApple3是的。該技術被稱爲[方法注入](https://github.com/google/guice/wiki/Injections#method-injection)。 –