来自多个组件的现场注入

Field injection from more than one components

在 Dagger2 中是否可以像下面这样从两个模块注入?

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 的依赖项。

如果您希望每个 class 使用多个组件,您可以使用配置方法手动设置字段。

@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());
    }
}