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

如何在Dagger2构造注入时向构造函数传递参数?

解决Dagger2构造注入带参数B的问题

咱们先梳理下你当前代码里的几个核心问题,然后一步步调整,实现你想要的依赖注入效果:

问题分析

  1. 冗余的Module:你的类B已经用@Inject标记了构造函数,这就告诉Dagger可以直接通过这个构造创建B实例,不需要额外写BProvider模块来手动new B(而且你原模块里的new B()还缺少构造参数,会编译报错)。
  2. 参数来源缺失:B的构造需要int参数,但Dagger不知道这个参数从哪来,必须明确告诉它参数的获取方式。
  3. Component方法错误:Component里的provideB(A objA)不是标准的注入方法,应该用inject(A a)来触发对A对象的依赖注入。

方案1:外部传入int参数(适配你A构造里的some_value)

这种情况适合参数需要从外部动态传入的场景(比如你A构造里的some_value),我们可以通过Component的Builder来传递这个参数:

1. 修正类B(保持构造注入即可)

class B {
    @Inject
    public B(int var) {
        other_method(var);
    }

    private void other_method(int var) {
        // 这里写你的业务逻辑
    }
}

2. 重构Component,添加Builder接收参数

@Component
public interface BComponent {
    // 定义注入方法,传入要注入的A对象
    void inject(A a);

    // 定义Builder,用于外部传入B构造需要的int参数
    @Component.Builder
    interface Builder {
        // 用@BindsInstance把外部传入的int绑定到Component中
        @BindsInstance
        Builder var(int var);

        BComponent build();
    }
}

3. 修正类A的初始化逻辑

class A {
    @Inject
    public B objectB;

    public A(int some_value) {
        // 创建Component时,把some_value传递给Builder
        BComponent bComponent = DaggerBComponent.builder()
                .var(some_value)
                .build();
        // 触发依赖注入,Dagger会自动创建带参数的B实例并赋值给objectB
        bComponent.inject(this);
    }
}

方案2:通过Module提供固定/预设的int参数

如果你的int参数是固定值,或者需要从其他地方统一获取,可以写一个Module来提供这个参数:

1. 新增提供int参数的Module

@Module
public class IntValueModule {
    @Provides
    public int provideIntValue() {
        return 100; // 这里可以是固定值,或者从配置、其他依赖中获取
    }
}

2. 关联Module的Component

@Component(modules = IntValueModule.class)
public interface BComponent {
    void inject(A a);
}

3. 类A的简化初始化

class A {
    @Inject
    public B objectB;

    public A(int some_value) {
        // 直接创建Component,Dagger会从Module中获取int参数创建B
        BComponent bComponent = DaggerBComponent.create();
        bComponent.inject(this);
    }
}

关键要点总结

  • 构造注入优先:当类有@Inject构造时,Dagger会优先用这个构造创建实例,无需额外的@Provides方法,除非你需要自定义实例逻辑。
  • 参数必须明确来源:构造函数的参数要么通过@BindsInstance从外部传入,要么通过Module提供,Dagger不会凭空生成参数值。
  • 注入方法规范:Component中需要定义inject(目标类)方法,调用该方法才能触发对目标对象的依赖注入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:38:05