我正在尝试将Dagger 2添加到我的Android项目中。我想我理解了构建图形的概念。那时我在黑暗中射击,这就是我出错的地方 所有内容都会编译,但在运行时注入的字段为空。
我试图通过将Presenter注入我的MainActivity来开始。我已经编写了以下代码,并希望得到一些帮助,找出我出错的地方。
My PresenterModule.java:
@Module
public class PresenterModule {
@Provides MainActivityPresenter providesMainActivityPresenter() {
return new DefaultMainActivityPresenter();
}
}
我的Application类,它还包含遵循Dagger2示例代码的我的Component:
public class App extends Application {
private PresenterComponent component;
@Singleton
@Component(modules = PresenterModule.class)
public interface PresenterComponent {
void inject(App app);
void inject(MainActivity activity);
}
@Override public void onCreate() {
Log.d("App.java", "Starting Application");
super.onCreate();
component = DaggerApp_PresenterComponent.builder()
.presenterModule(new PresenterModule())
.build();
component.inject(this);
}
public PresenterComponent component() {
return component;
}
}
最后是我的MainActivity。
public class DefaultMainActivity
extends ActionBarActivity
implements MainActivity
{
@Inject MainActivityPresenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((App)getApplication()).component().inject(this);
mPresenter.getCurrentDetailLineNumber();
setContentView(R.layout.base_layout);
getSupportActionBar();
mContainer = (Container) findViewById(R.id.container);
mPresenter.requestCurrentScreen();
}
要注入的实际对象是接口的实现,但另一个是POJO对象:
public class DefaultMainActivityPresenter implements MainActivityPresenter {
private static final int SCREEN_BROWSER = 0;
private static final int SCREEN_DETAIL = 1;
LineNumber mCurrentDetailLineNumber;
int mCurrentScreen;
@Inject
public DefaultMainActivityPresenter() {
}
...
}
答案 0 :(得分:6)
将PresenterComponent更改为以下内容将解决您的问题:
@Singleton
@Component(modules = PresenterModule.class)
public interface PresenterComponent {
void inject(App app);
void inject(DefaultMainActivity activity);
}
这是由于协方差: 虽然类型的成员注入方法将接受其子类型的实例,但只会注入参数类型的注入注释成员及其超类型;亚型的成员不会。例如,给定以下类型,当它传递给成员注入方法injectSelf(自我实例)时,只有a和b将被注入到Child的实例中:
class Parent {
@Inject A a;
}
class Self extends Parent {
@Inject B b;
}
class Child extends Self {
@Inject C c;
}