特点
Hilt就是Android团队联系了Dagger2团队,一起开发出来的一个专门面向Android的依赖注入框架。
相比于Dagger2,Hilt最明显的特征就是:
- 简单。
- 提供了Android专属的API。
Hilt做的优化包括:
- 无需编写大量的Component代码
- Scope也会与Component自动绑定
- 预定义绑定,例如 Application与Activity
- 预定义的限定符,例如@ApplicationContext与@ActivityContext
基本配置
1
| classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
|
1 2 3 4 5 6
| apply plugin: 'dagger.hilt.android.plugin' //hilt implementation "com.google.dagger:hilt-android:2.28-alpha" annotationProcessor "com.google.dagger:hilt-android-compiler:2.28-alpha" //kotlin //katp "com.google.dagger:hilt-android-compiler:2.28-alpha"
|
1 2 3 4 5
| //支持java8 compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }
|
Hilt 目前支持以下 Android 类。
Application
Activity
Fragment
View
Service
BroadcastReceiver
基本使用
1. 提供一个对象
1 2
| public class HttpObject { }
|
2. 编写Module
1 2 3 4 5 6 7 8
| @InstallIn(ActivityComponent.class) @Module public class HttpModule { @Provides public HttpObject getHttpObject(){ return new HttpObject(); } }
|
3. 注入到Activity
1 2 3 4 5 6
| @AndroidEntryPoint public class MainActivity extends AppCompatActivity { @Inject HttpObject httpObject; @Inject HttpObject httpObject2;
|
4. Application中注册
1 2 3 4
| @HiltAndroidApp public class MyApplication extends Application {
}
|
5. 全局单例使用
1 2 3 4 5 6 7 8 9 10
| @InstallIn(ApplicationComponent.class) @Module public class HttpModule {
@Provides @Singleton public HttpObject getHttpObject(){ return new HttpObject(); } }
|
注意:Hilt注入的字段是不可以声明成private
为接口注入实例
1 2 3
| public interface AnalyticsService { void analyticsMethods(); }
|
1 2 3 4 5 6 7
| public class AnalyticsServiceImpl implements AnalyticsService { ... @Inject AnalyticsServiceImpl(...) { ... } }
|
1 2 3 4 5 6 7 8 9
| @Module @InstallIn(ActivityComponent.class) public abstract class AnalyticsModule {
@Binds public abstract AnalyticsService bindAnalyticsService( AnalyticsServiceImpl analyticsServiceImpl ); }
|
Component与Scope
Hilt 提供了以下组件:
组件生命周期
同时还提供了相应的作用域
注意事项
实现有使用gradle插件做字节码插桩。
C:\Users\Administrator\.gradle\caches\modules-2\files-2.1\com.google.dagger\hilt-android-gradle-plugin\2.28-alpha\eb33a043b2bbdc7cdee3c851d0f8532bfd3645a5\hilt-android-gradle-plugin-2.28-alpha-sources\dagger\hilt\android\plugin
应用
Hilt网络隔离层设计