在集成匕首2时,我面临一个问题。 Dagger2无法在基类中注入依赖项。请执行以下代码:
public abstract class BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
public class MainActivity extends BaseActivity {
@Inject
MainPresenter presenter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getComponent().inject(this);
}
}
public abstract class BasePresenter {
@Inject
BaseRepository baseRepository;
}
public class MainPresenter extends BasePresenter {
@Inject
MainRepository mainRepository;
}
@Component(modules = MainModule.class)
public interface MainComponent {
// void inject(BaseActivity baseActivity);
void inject(MainActivity mainActivity);
}
@Module(includes = RepoModule.class)
public class MainModule {
@Provides
public MainPresenter getMainPresenter() {
return new MainPresenter();
}
}
@Module
public class RepoModule {
@Provides
public BaseRepository getBaseRepository() {
return new BaseRepository();
}
@Provides
public MainRepository getMainRepository() {
return new MainRepository();
}
}
在上面的代码片段中,presenter和mainRepository对象被注入。但是,不会注入BasePresenter类中的baseRepository对象。在构建gradle时,Dagger2不会引发任何错误。应用运行后,它返回null:(
我在哪里犯错?还是Dagger2提供了这种在基类中注入依赖项的方法?请帮帮我。 谢谢!