![](/img/trans.png)
[英]How to fill an array with 10 even integers following some user provided integer?
[英]How to have some injections and some provided classes into a provided class
我正在開始使用Dagger 2,並嘗試找出如何使@Inject
和@Provides
一起良好地工作。 注入頂級類時,很容易使所有工作正常。 像這樣:
class TopLevelClass {
@Inject
SecondaryClass1 class1;
private final SecondaryClass2 class2;
@Inject
TopLevelClass(SecondaryClass2 class2) {
this.class2 = class2;
}
}
@Module
class MyModule {
@Provides
SecondaryClass2 provideSecondaryClass2() {
return new SecondaryClass2();
}
}
但是,當我也必須為頂級類創建@Provides
方法時,一切都停止工作。 像這樣:
class TopLevelClass {
@Inject
SecondaryClass1 class1;
private final SecondaryClass2 class2;
TopLevelClass(SecondaryClass2 class2) {
this.class2 = class2;
}
}
@Module
class MyModule {
@Provides
TopLevelClass provideTopLevelClass(SecondaryClass2 class2) {
return new TopLevelClass(class2);
}
@Provides
SecondaryClass2 provideSecondaryClass2() {
return new SecondaryClass2();
}
}
在此示例中,我發現從不會注入SecondaryClass1,因此在嘗試訪問NPE時會得到一個NPE。 對於提供的頂級課程,我應該采用其他方法嗎?
PS,我認為這無關緊要,但以下是我使用的組件,以防萬一:
@Component(modules = {MyModule.class})
interface MyComponent {
TopLevelClass getTopLevelClass();
}
謝謝!
您有2個選擇:
@Provides
注釋的方法),即可使用該對象,而無需任何代碼。 這就是匕首閃耀的地方。 @Provides
注釋的方法返回它之前,確保它已正確設置。 我不知道為什么您會選擇第二個選項,或者為什么甚至在可以使用構造函數時甚至希望使用字段注入,但是,正如您所發現的,如果您手動構造賓語。 生成的Dagger代碼均不會運行-您必須自己執行此操作。
我想到的一種方法是請求組件,然后注入對象。
@Provides
TopLevelClass provideTopLevelClass(SecondaryClass2 class2, MyComponent component) {
TopLevelClass tlc = new TopLevelClass(class2);
component.inject(tlc);
return tlc;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.