简体   繁体   中英

How to use dagger2 subcomponent?

According to official documents: https://google.github.io/dagger/subcomponents.html ,I add a subcomponent in @Module, like this:

@Module(subcomponents = {MainActivityComponent.class})
public class ContextModule {

    private Context mContext;

    public ContextModule(Context context) {
        mContext = context;
    }

    @Provides
    public Context provideContext() {
        return mContext;
    }

}

And declare my component and subcomponent like this:

@Component(modules = ContextModule.class)
public interface AppComponent {
    Context provideContext();

    MainActivityComponent getMainActivityComponent();
}

@Subcomponent(modules = {HardwareModule.class, SoftwareModule.class})
public interface MainActivityComponent {
    void injectMainActivity(MainActivity activity);
}

But the code can not be compiled successfully. The error is this:

Error:(11, 1) : com.kilnn.dagger2.example.MainActivityComponent doesn't have a @Subcomponent.Builder, which is required when used with @Module.subcomponents

I don't know how to write a @Subcomponent.Builder , and if i remove the subcomponent declare in @Module, everything is ok. So i don't know what is the right way to use subcomponent.

Actually, the error is quite descriptive, all you need to do is add the Builder to your Subcomponent like this:

MainActivityComponent.class

@Subcomponent.Builder
interface Builder {
     MainActivityComponent build();
}

For your current implementation, and since you don't have special dependencies you don't really need the Subcomponent .

Note: For convention's sake I recommend you to rename your Subcomponent to MainActivitySubcomponent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM