【发布时间】:2016-05-04 14:22:05
【问题描述】:
我正在开发 Dagger 2,但遇到了依赖注入问题。我会给你一个想法来解决这个问题。我有一个如下所示的 ApplicationComponent。
@Singleton
@Component(modules = {AppModule.class, MySubComponent.class})
public interface ApplicationComponent {
void inject(Application app);
List<Integer> pattern;
MySubComponent subcomponent();
}
如您所见,我在上述组件中定义了一个子组件。
ApplicationComponent comp = DaggerApplicationComponent.builder()
.appModule(new ApplicationModule())
.mySubModule(new MySubModule())
.build();
这就是我创建应用程序组件实例的方式。
这是子组件
@Singleton
@Subcomponent(modules = MySubModule.class)
public interface MySubComponent {
void inject(AClass obj);
INeedThis ineedthis();
}
@Module
public class MySubComponent {
@Provides
@Singleton
INeedThis provideINeedThis() {
return new INeedThis();
}
}
然后我创建了另一个组件,LoginComponent 并以 ApplicationComponent 作为依赖项
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface PerActivity{}
@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = LoginModule.class)
public interface LoginComponent {
void inject(FirstActivity activity);
}
我创建了如下的 LoginComponent 实例。
LoginComponent comp = DaggerLoginComponent.builder().loginModule(new LoginModule().applicationComponent(appComponentObject).build();
当我在 FirstActivity 中注入 INeedThis 对象时会出现问题。我的假设是因为 LoginComponent 有一个 ApplicationComponent 的依赖项,它有一个子组件 MySubComponent,应该注入 INeedThis 对象。但实际上,它没有这样做,我收到以下错误。
INeedThis cannot be provided without an @Provides- or @Produces- annotated methods.
我阅读了很多关于 dagger 2 子组件的帖子。但是,它们并没有按预期工作。我有什么遗漏吗?
【问题讨论】: