匕首 2:如果没有带@Provides注释的方法,则无法提供
2022-09-01 06:13:15
我刚刚开始学习dagger2,并遇到了一个奇怪的问题,对我来说就像一个错误。这是模块:
@Module
public class SimpleModule {
@Provides
Cooker providerCooker() {
return new Cooker("tom", "natie");
}
}
元件:
@Component(modules = SimpleModule.class)
public interface SimpleComponent {
void inject(DaggerTestActivity activity);
}
接口:
public interface CoffeeMaker {
String makeCoffee();
}
实现:
public class SimpleMaker implements CoffeeMaker {
Cooker mCooker;
@Inject
public SimpleMaker(Cooker cooker) {
this.mCooker = cooker;
}
@Override
public String makeCoffee() {
return mCooker.makeCoffee();
}
}
炊具:
public class Cooker {
String name;
String coffeeKind;
public Cooker(String name, String coffeeKind) {
this.name = name;
this.coffeeKind = coffeeKind;
}
public String makeCoffee() {
return name + "make" + coffeeKind;
}
}
咖啡机:
public class CoffeeMachine {
CoffeeMaker mMaker;
@Inject
public CoffeeMachine(CoffeeMaker coffeeMaker) {
this.mMaker = coffeeMaker;
}
public String makeCoffee() {
return mMaker.makeCoffee();
}
}
就这样。我在活动中使用它。在这里遇到奇怪的问题:
@Inject
CoffeeMachine mCoffeeMachine;
我从Dagger 2编译器得到的错误如下:
Error:(14, 10) com.wyyc.daggertest.CoffeeMaker cannot be provided without an @Provides-annotated method.
com.wyyc.zqqworkproject.DaggerTestActivity.mCoffeeMachine
[injected field of type: com.wyyc.daggertest.CoffeeMachine mCoffeeMachine]
com.wyyc.daggertest.CoffeeMachine.<init>(com.wyyc.daggertest.CoffeeMaker coffeeMaker)
所有这些情况看起来都非常奇怪,我想听听更有经验的Dagger 2用户的一些意见。