为什么以下代码无法编译并出现以下错误,应该采取哪些措施来修复它?
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 {
}
答案 0 :(得分:3)
要使其有效,我只需将@Qualifier
更改为@Scope
中的SubScope
:
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface SubScope {
}