我有这个:
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
的自行车,但车轮没有注入。但是,如果我使用Bike
注释@Inject
构造函数并删除BikeModule.provideBike()
方法,那么轮子执行会被注入。所以问题似乎是关于注入在@Provides
方法中创建的对象,而不是由Dagger本身创建。
有没有办法告诉Dagger注入一个提供的对象?
答案 0 :(得分:1)
像这样改写:
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");
}
}