在 Dagger2 中是否可以像下面这样从两个模块注入(inject)?
public class MyActivity extends Activity {
@Inject ProvidedByOne one;
@Inject ProvidedByTwo two;
public void onCreate(Bundle savedInstance) {
((App) getApplication()).getOneComponent().inject(this);
((App) getApplication()).getSecondComponent().inject(this);
}
}
我有两个独立的模块,无法使其工作。我有错误:
Error:(16, 10) error: com.test.dagger.module.TwoModule.Two cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method. com.test.activity.MoreActivity.two [injected field of type: com.test.dagger.module.TwoModule.Two two]
Error:(16, 10) error: com.test.dagger.module.OneModule.One cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method. com.test.activity.MoreActivity.one [injected field of type: com.test.dagger.module.OneModule.One one]
public class MoreActivity extends SingleFragmentActivity {
@Inject OneModule.One one;
@Inject TwoModule.Two two;
@Override
protected Fragment createFragment() {
((App)getApplication()).getOneComponent().inject(this);
((App)getApplication()).getTwoComponent().inject(this);
return SimpleFragment.newInstance(MoreActivity.class.getSimpleName());
}
}
@Module
public class OneModule {
public class One {
}
@Provides
@Singleton
One provideOne() {
return new One();
}
}
@Module
public class TwoModule {
public class Two {
}
@Provides
@Singleton
Two provideTwo() {
return new Two();
}
}
@Singleton
@Component(modules = OneModule.class)
public interface OneComponent {
void inject(MoreActivity activity);
}
@Singleton
@Component(modules = TwoModule.class)
public interface TwoComponent {
void inject(MoreActivity activity);
}
最佳答案
不,要使用字段注入(inject),您的组件需要能够提供所有用 @Inject
标记的依赖项。
如果您想在每个类中使用多个组件,您可以使用配置方法手动设置字段。
@Module
public class OneModule {
public class One {
}
@Provides
@Singleton
One provideOne() {
return new One();
}
}
@Module
public class TwoModule {
public class Two {
}
@Provides
@Singleton
Two provideTwo() {
return new Two();
}
}
@Singleton
@Component(modules = OneModule.class)
public interface OneComponent {
OneModule.One one();
}
@Singleton
@Component(modules = TwoModule.class)
public interface TwoComponent {
TwoModule.Two two();
}
和
public class MoreActivity extends SingleFragmentActivity {
OneModule.One one;
TwoModule.Two two;
@Override
protected Fragment createFragment() {
one = ((App)getApplication()).getOneComponent().one();
two = ((App)getApplication()).getTwoComponent().two();
return SimpleFragment.newInstance(MoreActivity.class.getSimpleName());
}
}
关于android - 来自多个组件的现场注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38450765/