LoginSignup
0
0

More than 3 years have passed since last update.

dagger2入門 - basic(@Inject & @Component)

Posted at

概要

  • dagger2入門 - 導入の仕方に、gradleよりdagger2の導入方法を紹介しました
  • 今回はdagger2の基本的な使い方を紹介します - @Inject@Component
  • 概念などをここに紹介しなくて、使い方を中心として話します

簡単な使い方

注入できるクラスを作成して、コンストラクタ前に@Injectを追記

class People @Inject constructor() {
    fun doWhat(): String {
        return "eat dinner"
    }
}

Componentを作成して注入先を指定

@Component
interface PComponent {
    fun into(home: Home)
}

インスタンス変数を用意

  • DaggerPComponentを生成されるクラス
class Home {
    @Inject lateinit var people: People

    fun doDinner() {
        DaggerPComponent.create().into(this)
        println(people.doWhat())
    }
}

結果

eat dinner

Process finished with exit code 0

もし注入用クラスにも引数必要場合

class Tool @Inject constructor() {
    fun withFork(): String {
        return "eat with fork"
    }
}

class People @Inject constructor(val tool: Tool) {
    fun doWhat(): String {
        return tool.withFork()
    }
}

結果

eat with fork

Process finished with exit code 0

遷移図

スクリーンショット 2019-12-20 21.36.08.png

サンプルコード

ひとつの問題

  • 導入したpackageのクラスに、コストラクタに@Injectを追記できません
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0