Dagger 2.10:子组件+自定义范围="如果没有@Inject构造函数或@ Provide-或@ Produces-annotated方法"

时间:2017-05-21 14:35:23

标签: java android dagger-2

为什么以下代码无法编译并出现以下错误,应该采取哪些措施来修复它?

Error:(9, 8) error: [SubComponent.inject(MainActivity)] java.lang.Integer cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method.
java.lang.Integer is injected at
MainActivity.abc
MainActivity is injected at
SubComponent.inject(activity)

TL; DR:我正在尝试创建一个与父组件不同的子组件,并将子组件的依赖项注入活动。

App.java

public class App extends Application {
    private AppComponent appComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        appComponent = DaggerAppComponent.create();
        appComponent.inject(this);
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
    }

    public AppComponent getAppComponent() {
        return appComponent;
    }

    public static App app(Context context) {
        return (App) context.getApplicationContext();
    }
}

AppComponent.java

@Singleton
@Component
public interface AppComponent {
    void inject(App app);

    SubComponent.Builder subComponent();
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Inject
    int abc;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        App.app(this).getAppComponent()
                .subComponent()
                .userModule(new SubModule())
                .build()
                .inject(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
    }
}

SubComponent.java

@SubScope
@Subcomponent(modules = {SubModule.class})
public interface SubComponent {
    void inject(MainActivity activity);

    @Subcomponent.Builder
    interface Builder {
        Builder userModule(SubModule module);

        SubComponent build();
    }
}

SubModule.java

@Module
public class SubModule {
    @Provides
    @SubScope
    public int provideAbc() {
        return 1;
    }
}

SubScope.java

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface SubScope {
}

1 个答案:

答案 0 :(得分:3)

要使其有效,我只需将@Qualifier更改为@Scope中的SubScope

@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface SubScope {
}