android.dagger使用

以注入OkHttpClient为例:

之前我们需要

@Module
class OkhttpModule {
    @Provides
    fun okhttpProvider():OkHttpClient{
        return OkHttpClient()
    }
}
@Component(modules = [OkhttpModule::class])
interface MainComponent {
    fun inject(activity: MainActivity)
}

之后在MainActivity中注入:

class MainActivity : AppCompatActivity() {
    @Inject
    lateinit var okhttpClient: OkHttpClient

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerMainComponent.create().inject(this)
        setContentView(R.layout.activity_main)
        Log.e("Tag" , "okhttpClient? ${this::okhttpClient.isInitialized}")
    }
}

以此为基础修改成dagger.android方式

所有依赖

    implementation 'com.google.dagger:dagger-android:2.24'
    // if you use the support libraries(就是你需要v4.Fragment就需要加上support包)
    implementation 'com.google.dagger:dagger-android-support:2.24'
    implementation("com.squareup.okhttp3:okhttp:4.2.0")
    kapt 'com.google.dagger:dagger-compiler:2.24'
    kapt 'com.google.dagger:dagger-android-processor:2.24'

添加AppComponent

@Component(modules = [AndroidInjectionModule::class, //dagger提供
    AndroidSupportInjectionModule::class,//dagger提供
    OkhttpModule::class,//之前的Module,用来提供okhttp实例
    ActivityBindingModule::class //用来绑定Activity
])
interface AppComponent : AndroidInjector
@Module
abstract class ActivityBindingModule {
    @ContributesAndroidInjector
    abstract fun bindingMainActivity():MainActivity
}

添加Application,并且继承DaggerApplication

DaggerAppComponent是自动生成的,需要build一下

class App : DaggerApplication() {
    override fun applicationInjector(): AndroidInjector {
        return DaggerAppComponent.create()
    }
}

修改MainActivity继承自Dagger系列Activity,然后就可以使用注入的实例了

class MainActivity : DaggerAppCompatActivity() {
    @Inject
    lateinit var okhttpClient: OkHttpClient
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.e("Tag" , "okhttpClient? ${this::okhttpClient.isInitialized}")
    }
}

 

你可能感兴趣的:(Android)