鑑於下面的例子:是否可以避免父類中的不必要注入?
class CustomView extends View {
@Inject
SomeObject mObject;
@Override
protected void onFinishInflate() {
super.onFinishInflate();
getApplicationComponent().inject(this);
}
}
class SecondaryCustomView extends CustomView {
@Inject
AnotherObject mAnotherObject;
@Override
protected void onFinishInflate() {
super.onFinishInflate();
getApplicationComponent().inject(this);
}
}
兩個自定義視圖可以在佈局被獨立地使用。第二個只比第一個更專業。如你所見,兩個都有注入的字段,都需要調用inject()。問題是,當SecondaryCustomView調用其inject()時,Dagger注入AnotherObject的實例和SomeObject的實例。在調用super.onFinishInflate()之後,它創建了SomeObject的第二個實例。這本身不是問題,但我們至少會創造不必要的對象。
有沒有辦法避免這種情況?有一種方式告訴Dagger注入了一個子類,那麼忽略父注入?
舉例來說,組件看起來是這樣的:
@Component(...)
public interface AppComponent {
void inject(CustomView);
void inject(SecondaryCustomView);
}
你還可以發佈你的組件的接口嗎? – azizbekian
這只是一個例子。如果您想知道注入對象的範圍,請考慮爲每次注入創建一個新實例。 – fhsilva
我感興趣接口方法簽名中'this'的類型是什麼。 – azizbekian