[英]Dagger 2: How to inject an object created within a @Provides method?
I've got this: 我有这个:
Bike.java Bike.java
public class Bike {
String serial;
@Inject
Wheels wheels;
public Bike(String serial) {
this.serial = serial;
}
}
BikeModule.java 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 BikeComponent.java
@Component(modules = BikeModule.class)
public interface BikeComponent {
Bike bike();
}
Now here's the problem: when I call BikeComponent.bike()
, I get a bike with the serial BIK-001
, as intended, but the wheels are not injected. 现在是问题所在:当我调用BikeComponent.bike()
,按预期得到了带有序列号BIK-001
的自行车,但未注入车轮。 However, if I annotate the Bike
constructor with @Inject
and remove the BikeModule.provideBike()
method, the wheels do get injected. 但是,如果我用@Inject
注释Bike
构造函数并删除BikeModule.provideBike()
方法,则车轮确实会被注入。 So the problem seems to be about injecting an object created within a @Provides
method, instead of created by Dagger itself. 因此,问题似乎出在注入在@Provides
方法中创建的对象,而不是Dagger本身创建的对象。
Is there a way to tell Dagger to inject a provided object? 有没有办法告诉Dagger注入提供的对象?
Rewrite like this: 像这样重写:
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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.