我正在尝试使用dagger在我的应用中实现依赖注入。我有类似"Simpler Android apps with Flow and Mortar"
中描述的结构我有一个DayScreen
课程:
@Layout(R.layout.day)
public class DayScreen extends DateScreen {
LocalDate date;
public DayScreen(LocalDate date) { this.date = date; }
@Override public String getMortarScopeName() { return getClass.getName(); }
@Override public Object getDaggerModule getModule() { retrun new Module(); }
@dagger.Module(addsTo = UiModule.class, injects = DayView.class, complete = false, library = true)
public class Module {
@Inject RestService api;
@Inject DateTimeFormatter formatter;
@Provides @Named("DayScreenDate") LocalDate provideDate(){
return date;
}
}
@Singleton
public class Presenter extends ViewPresenter<DayView> {
//@Inject RestService api;
//@Inject DateTimeFormatter formatter;
RestService api;
DateTimeFormatter formatter;
@Inject Presenter( RestService api, DateTimeFormatter formatter){
this.api = api;
this.formatter = formatter;
}
@Override
protected void onLoad(Bundle savedInstanceState) {
super.onLoad(savedInstanceState);
api.statisticsDay(DayScreen.this.date.format(formatter))
.observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(
resp -> getView().setData(resp.events),
err -> Log.e(TAG, err.getLocalizedMessage()),
() -> Log.v(TAG, "day stats received")
);
}
}
这里DateScreen
是一个摘要:
public abstract class DateScreen implements Blueprint {
protected LocalDate date;
public DateScreen() { this(LocalDate.now()); }
public DateScreen(LocalDate date) { this.date = date; }
public LocalDate getDate() { return date; }
public void setDate(LocalDate date){ this.date = date; }
}
我尝试通过构造函数和trough字段注入在Module和Presenter中注入api
和formatter
,但它会咳嗽同样的错误error: Can't inject a non-static inner class:...
有人知道为什么需要静态课程吗?是否有任何变化使我上面提到的文章无关紧要?
感谢。
答案 0 :(得分:2)
非静态类需要实例化封闭实例。这阻止了DI框架实例化它们。如果您有嵌套类,那么在任何情况下将它们设置为静态都是个好主意。
如果您的嵌套类本质上依赖于封闭的实例,那么您必须重构以使类静态化并定义一个显式构造函数来获取封闭类的实例。