Android官方依赖注入框架Hilt接入与使用

5,904 阅读1分钟

google官方依赖注入框架,基于dagger

添加和使用

project里的 build.gradle 里添加hilt的依赖

在最上层的build.gradle里添加hilt的版本号

buildscript {
    ext.kotlin_version = '1.3.61'
    ext.hiltVersion = '2.28-alpha'
  .....
  
      dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "com.google.dagger:hilt-android-gradle-plugin:$hiltVersion"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
      }
  • 添加hilt的version,ext.hiltVersion='2.28-alpha'
  • 添加 gradle 插件  classpath "com.google.dagger:hilt-android-gradle-plugin:$hiltVersion"

在app的 build.gradle 里添加插件和依赖

apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'

implementation "com.google.dagger:hilt-android:$hiltVersion"
kapt "com.google.dagger:hilt-android-compiler:$hiltVersion"

在自定义application上打上 @HiltAndroidApp 标签

@HiltAndroidApp
class MyApplication : Application() {
    ...
}

基本配置已经完成了,接下来只需要在要使用的地方打上对应的标签就可以了。

几个理解

@Inject标签

@Inject标签有两个作用,如果打在field说明这个field需要注入,如果打在constructor上就说明这个constructor可以提供需要注入的对象

@InstallIn的理解

这里主要是为了给那些无法给constructor添加@inject注解的类提供实例,然后提供实例需要有一个类似生命周期,或者引用权限的问题,这个注解就是为了给这些生成的对象限制生命周期的,文档里给的是容器这个字,这个理解也很对。

如果无法直接对constructor打注解,可以使用@Module来提供对象生成

codelabs.developers.google.com/codelabs/an…

可能遇到的问题

在与Arouter一起使用的时候报错

public final class MainFragment BaseFragment {
             ^
  Expected @AndroidEntryPoint to have a value. Did you forget to apply the Gradle Plugin?
  [1;31m[Hilt] Processing did not complete. See error above for details.[0m

如果你是纯kotlin的项目,可以直接去掉这个compileOptions,这样就没有冲突了。

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "xxxx"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 4
        versionName "1.1.2"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

//        javaCompileOptions {
//            annotationProcessorOptions {
//                arguments = [AROUTER_MODULE_NAME: project.getName()]
//            }
//        }
    }

参考答案:stackoverflow.com/a/62619732/…

参考文档: