介绍
Dagger Hilt (这名字起的溜...........)
官方描述其设计目的:
- To simplify Dagger-related infrastructure for Android apps.
- To create a standard set of components and scopes to ease setup, readability/understanding, and code sharing between apps.
- To provide an easy way to provision different bindings to various build types (e.g. testing, debug, or release).
简单说就是Dagger Android的瘦身包,使依赖注入在Android开发中标准化、简单化。
集成
首先在项目级别的build.gradle文件中添加以下内容,这将使我们能够访问hilt gradle插件:
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
然后在应用程序级别的build.gradle文件并应用此插件:
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'
最后,在应用程序级别build.gradle文件中添加所需的hilt依赖项:
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha01'
kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha01'
这样Hilt就可以使用了。
Hilt Application
按照官方要求,首先需要在自定义的Application类中添加@HiltAndroidApp
注解:
@HiltAndroidApp
class APP:Application()
这有什么作用?以下来自官方描述:
All apps using Hilt must contain an Application
class annotated with @HiltAndroidApp
. @HiltAndroidApp
kicks off the code generation of the Hilt components and also generates a base class for your application that uses those generated components. Because the code generation needs access to all of your modules, the target that compiles your Application
class also needs to have all of your Dagger modules in its transitive dependencies.
Just like other Hilt Android entry points, Applications are members injected as well. This means you can use injected fields in the Application after super.onCreate()
has been called.
在Daager2
中,需要Application继承DaggerApplication
,并且还需要创建Application的Module
。
这里只需要使用@HiltAndroidApp
的注解就可以完成对Application的依赖注入,由Hilt gradle插件生成对应的文件
构建后我们看到在 app/build/generated/source/kapt/debug/
目录下生成了一个Hilt_APP
的抽象类:
/**
* A generated base class to be extended by the @dagger.hilt.android.HiltAndroidApp annotated class. If using the Gradle plugin, this is swapped as the base class via bytecode transformation. */
@Generated("dagger.hilt.android.processor.internal.androidentrypoint.ApplicationGenerator")
public abstract class Hilt_APP extends Application implements GeneratedComponentManager