2016-04-26 8 views
0

Dagger2でどのように動作するのか理解するために遊んでいます。私はちょうど "hello dagger2"基本プロジェクトを作成しましたが、クラッシュします。こんにちはDagger2がAndroidスタジオでクラッシュする

私は3つのクラスを持っています:パン、小麦粉と水。パンは、小麦粉と水に依存しています。

クラスのパン:

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(); 
} 

Iはfacing amエラーが:私が間違っdoing am What

Error:(13, 11) error: com.example.llisas.testingdagger2.model.Water cannot be provided without an @Inject constructor or from an @Provides-annotated method. com.example.llisas.testingdagger2.module.BreadModule.provideBread(com.example.llisas.testingdagger2.model.Water water, com.example.llisas.testingdagger2.model.Flour flour) [parameter: com.example.llisas.testingdagger2.model.Water water]

答えて

0

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); 
} 
+0

おかげで、両方の方法で作成したが、整数を受け取ります(量としての量)と他の誤差があります。シングルトンを提供する Water provideWater(int quantity){ return new Water(quantity); } – JoCuTo

+0

エラー:(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 flour) [パラメータ:com.example.llisas .testingdagger2.model.Water water] com.example.llisas.testingdagger2.module.BreadModule.provideWater(int quantity) [パラメータ:int量] – JoCuTo

+0

メソッドにパラメータ(この場合は整数)がある限り、 provideメソッドがパラメータを持たない限り、それらを提供し続ける必要があります。整数の場合、提供している整数の種類を区別するために@Name( "description")注釈を追加する必要があります。 – AgileNinja

関連する問題