匕首2:如何注入@provides方法中创建的对象



我已经知道了:

bike.java

public class Bike {
    String serial;
    @Inject
    Wheels wheels;
    public Bike(String serial) {
        this.serial = serial;
    }
}

bikemodule.java

@Module
public class BikeModule {
    @Provides
    public Bike provideBike() {
        return new Bike("BIK-001");
    }
    @Provides
    public Wheels provideWheels() {
        return new Wheels("WLS-027");
    }
}

bikecomponent.java

@Component(modules = BikeModule.class)
public interface BikeComponent {
    Bike bike();
}

现在是问题:当我致电BikeComponent.bike()时,我会根据预期使用串行BIK-001的自行车,但是车轮未注入。但是,如果我用@Inject注释Bike构造函数并删除BikeModule.provideBike()方法,则注入车轮 do 。因此,问题似乎是关于注入@Provides方法中创建的对象,而不是由dagger本身创建。

有没有办法告诉dagger注入提供的对象?

这样的重写:

public class Bike {
    private final String serial;
    private final Wheels wheels;
    @Inject
    public Bike(String serial, Wheels wheels) {
        this.serial = serial;
        this.wheels = wheels;
    }
}
@Module
public final class BikeModule {
    @Provides
    public static Bike provideBike(Wheels wheels) {
        return new Bike("BIK-001", wheels);
    }
    @Provides
    public static Wheels provideWheels() {
        return new Wheels("WLS-027");
    }
}

相关内容

最新更新