有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Dagger 2.10:Subcomponent+Custom scope=“如果没有@Inject构造函数或@Provides或@Producesannotated方法,就无法提供”

为什么下面的代码无法编译并出现以下错误,以及应该做些什么来修复它

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:我试图创建一个子组件,其作用域与父组件不同,并将子组件的依赖项注入到活动中


应用程序。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();
}

主要活动。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);
    }
}

子组件。java

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

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

        SubComponent build();
    }
}

子模块。java

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

子镜。java

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

共 (1) 个答案

  1. # 1 楼答案

    为了让它工作,我只需要在SubScope中把@Qualifier改成@Scope

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