You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dagger教程编译报错:main.Database.Account无法提供的解决求助

问题描述

完成Dagger官方教程至Withdraw Command章节时,编译程序出现如下错误:

java: [Dagger/MissingBinding] main.Database.Account cannot be provided without an @Inject constructor or an @Provides-annotated method.
main.Database.Account is injected at
main.DepositCommand(account, …)
main.DepositCommand is injected at
main.UserCommandsModule.depositCommand(command)
java.util.Map<java.lang.String,main.Command> is injected at
main.CommandRouter(commands)
main.CommandRouter is injected at
main.CommandProcessor(firstCommandRouter)
main.CommandProcessor is requested at
main.CommandProcessorFactory.commandProcessor() It is also requested at:
main.WithdrawCommand(…, account, …) The following other entry points also depend on it:
main.UserCommandsRouter.router() [main.CommandProcessorFactory → main.UserCommandsRouter]

问题原因与解决步骤

问题原因

Dagger无法在根组件CommandProcessorFactory中提供Account实例——Account是用户登录后通过UserCommandsRouter子组件绑定的上下文对象,而你错误地将包含deposit/withdraw命令的UserCommandsModule添加到了根组件中,导致根组件试图为这些命令注入Account,但根组件中并没有Account的绑定逻辑。

解决步骤

  1. 移除根组件对UserCommandsModule的依赖
    修改CommandProcessorFactory的@Component注解,删除UserCommandsModule.class——deposit/withdraw命令属于登录后的子路由,不应出现在根组件的全局命令集合中:

    @Singleton
    @Component(modules = {
            LoginCommandModule.class,
            HelloWorldModule.class,
            SystemOutModule.class,
            UserCommandsRouter.InstallationModule.class,
            AmountsModule.class
           })
    public interface CommandProcessorFactory {
        CommandProcessor commandProcessor();
    }
    
  2. 确认子组件配置正确
    你的UserCommandsRouter子组件已经正确包含UserCommandsModule,这部分无需修改,它会在用户登录时通过@BindsInstance注入当前用户的Account,为deposit/withdraw命令提供依赖:

    @Subcomponent(modules = { AmountsModule.class, UserCommandsModule.class})
    interface UserCommandsRouter {
        CommandRouter router();
    
        @Subcomponent.Factory
        interface Factory {
            UserCommandsRouter create(@BindsInstance Account account);
        }
    
        @Module(subcomponents = UserCommandsRouter.class)
        interface InstallationModule {}
    }
    

完成上述修改后,根组件的命令集合仅包含hello和login命令,deposit/withdraw命令仅在用户登录后由子组件提供,Dagger就能正确解析Account的依赖,编译错误即可解决。

内容的提问来源于stack exchange,提问作者Mohammad AttarZoghy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 07:26:59