java – Dagger 2:如果没有@ Provide-annotated方法,则无法提供

前端之家收集整理的这篇文章主要介绍了java – Dagger 2:如果没有@ Provide-annotated方法,则无法提供前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚刚开始学习dagger2,面对一个看起来像个bug的奇怪问题.这是模块:
@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用户的一些意见.

解决方法

您的CoffeeMachine需要CoffeeMaker.并且您已声明Dagger将通过使用@Inject注释构造函数来处理向CoffeeMachine提供依赖性.但达格说:

CoffeeMaker cannot be provided without an @Provides-annotated method

因为您没有在任何地方指定应如何创建CoffeeMaker对象. @Injecting SimpleMaker是不够的,因为SimpleMaker!= CoffeeMaker.因此,你必须明确指出,当Dagger想要CoffeeMaker时,然后向他提供SimpleMaker.

将您的模块更改为:

@Module
public class SimpleModule {

    @Provides
    Cooker providerCooker() {
        return new Cooker("tom","natie");
    }

    @Provides
    CoffeeMaker provideCoffeeMaker(Cooker cooker) {
        return new SimpleMaker(cooker);
    }

}
原文链接:https://www.f2er.com/java/129455.html

猜你在找的Java相关文章