【问题标题】:Hello Dagger2 crashes on Android Studio你好 Dagger2 在 Android Studio 上崩溃
【发布时间】:2016-04-26 18:32:58
【问题描述】:

我正在玩 Dagger2 以了解它是如何工作的。我刚刚创建了一个“hello dagger2”基本项目,但它崩溃了

我有三个课程:面包、面粉和水。面包依赖于面粉和水。

类面包:

    public class Bread {

    private Water water;
    private Flour flour;

    @Inject
    public Bread (Water water, Flour flour){
        this.water = water;
        this.flour = flour;
    }
}

类水:

public class Water {

    int waterQuantity;

    public Water(int waterQuantity){
    this.waterQuantity = waterQuantity;
    }
}

面粉类:

    public class Flour {

    private int flourQuantity;

    public Flour(int flourQuantity){
        this.flourQuantity = flourQuantity;
    }
}

我也实现了模块和组件

模块:

@Module
public class BreadModule {

    @Provides @Singleton
    Bread provideBread(Water water, Flour flour){
     return new Bread(water, flour);
    }
}

评论:

@Singleton
@Component (modules = {BreadModule.class})
public interface BreadComponent {

    Bread getBread();
}

我面临的错误是:

错误:(13, 11) 错误:com.example.llisas.testingdagger2.model.Water 如果没有 @Inject 构造函数或从 @提供带注释的方法。 com.example.llisas.testingdagger2.module.BreadModule.provideBread(com.example.llisas.testingdagger2.model.Water 水,com.example.llisas.testingdagger2.model.Flour 面粉) [参数:com.example.llisas.testingdagger2.model.Water 水]

我做错了什么?

【问题讨论】:

    标签: android dagger-2


    【解决方案1】:

    在尝试提供Bread 时,Dagger2 需要WaterFlour 类型的对象。您需要在模块中添加提供WaterFlour 的@Provide 方法。

    例如:

    @Provides
    Water provideWater() {
         return new Water(1); // instead of 1, you can add any other default value
    }
    

    如果你在这个方法中有一个整数,你也必须提供它,如下所示:

    @Provides @Named("defaultWaterQuantity")
    int provideWaterQuantity() {
        return 1;
    }
    
    @Provides
    Water provideWater(@Named("defaultWaterQuantity") int waterQuantity){
         return new Water(waterQuantity);
    }
    

    【讨论】:

    • 谢谢,这两个方法都创建了,接收一个整数(数量作为参数)和其他错误。提供单例水 provideWater(int quantity){ return new Water(quantity); }
    • 错误:(13, 11) 错误: java.lang.Integer 不能在没有 Inject 构造函数或提供注释的方法的情况下提供。 com.example.llisas.testingdagger2.module.BreadModule.provideBread(com.example.llisas.testingdagger2.model.Water water, com.example.llisas.testingdagger2.model.Flour 面粉) [参数:com.example.llisas.testingdagger2 .model.Water water] com.example.llisas.testingdagger2.module.BreadModule.provideWater(int quantity) [参数:int quantity]
    • 只要您的方法有参数(在本例中为整数),您就需要继续提供它们,直到提供方法没有参数。对于整数,您必须添加 @Name("description") 注释以区分您提供的不同类型的整数
    • 很抱歉,我不明白你的意思。能否请您添加一段代码作为示例
    • @JeCuRo 请检查编辑,看看您是否有任何问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多