Hilt依赖注入 #

一、Hilt概述 #

Hilt是Google推出的Android依赖注入框架,基于Dagger构建,简化了依赖注入的配置。

1.1 Hilt的优势 #

  • 减少样板代码
  • 编译时验证
  • 与Android组件集成
  • 支持ViewModel

1.2 添加依赖 #

kotlin
// 项目级build.gradle
plugins {
    id("com.google.dagger.hilt.android") version "2.50" apply false
}

// 模块级build.gradle
plugins {
    id("com.google.dagger.hilt.android")
    id("kotlin-kapt")
}

dependencies {
    implementation("com.google.dagger:hilt-android:2.50")
    kapt("com.google.dagger:hilt-compiler:2.50")
    
    // ViewModel支持
    implementation("androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03")
    kapt("androidx.hilt:hilt-compiler:1.0.0")
}

二、基本使用 #

2.1 Application配置 #

kotlin
@HiltAndroidApp
class MyApp : Application()

2.2 Activity注入 #

kotlin
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    
    @Inject
    lateinit var repository: UserRepository
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // repository已自动注入
        repository.loadData()
    }
}

2.3 Fragment注入 #

kotlin
@AndroidEntryPoint
class MainFragment : Fragment() {
    
    @Inject
    lateinit var repository: UserRepository
}

三、依赖提供 #

3.1 构造函数注入 #

kotlin
class UserRepository @Inject constructor(
    private val apiService: ApiService,
    private val userDao: UserDao
) {
    fun getUsers(): List<User> {
        // ...
    }
}

3.2 模块提供 #

kotlin
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
    
    @Provides
    @Singleton
    fun provideOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(HttpLoggingInterceptor())
            .build()
    }
    
    @Provides
    @Singleton
    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .baseUrl("https://api.example.com/")
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
    
    @Provides
    @Singleton
    fun provideApiService(retrofit: Retrofit): ApiService {
        return retrofit.create(ApiService::class.java)
    }
}

3.3 数据库模块 #

kotlin
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
    
    @Provides
    @Singleton
    fun provideDatabase(@ApplicationContext context: Context): AppDatabase {
        return Room.databaseBuilder(
            context,
            AppDatabase::class.java,
            "app_database"
        ).build()
    }
    
    @Provides
    fun provideUserDao(database: AppDatabase): UserDao {
        return database.userDao()
    }
}

四、组件与作用域 #

4.1 组件层次 #

组件 作用域 创建时机
SingletonComponent @Singleton Application创建
ActivityComponent @ActivityScoped Activity创建
FragmentComponent @FragmentScoped Fragment创建
ViewComponent @ViewScoped View创建
ViewModelComponent @ViewModelScoped ViewModel创建

4.2 使用作用域 #

kotlin
@ActivityScoped
class UserManager @Inject constructor(
    private val activity: Activity
) {
    // 每个Activity一个实例
}

@Singleton
class UserRepository @Inject constructor(
    private val apiService: ApiService
) {
    // 应用全局单例
}

4.3 组件入口点 #

kotlin
@EntryPoint
@InstallIn(SingletonComponent::class)
interface RepositoryEntryPoint {
    fun userRepository(): UserRepository
}

// 在非Hilt管理的类中获取依赖
val appContext = context.applicationContext as Context
val hiltEntryPoint = EntryPointAccessors.fromApplication(
    appContext,
    RepositoryEntryPoint::class.java
)
val userRepository = hiltEntryPoint.userRepository()

五、限定符 #

5.1 自定义限定符 #

kotlin
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class AuthInterceptor

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class LoggingInterceptor

5.2 使用限定符 #

kotlin
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
    
    @AuthInterceptor
    @Provides
    fun provideAuthInterceptor(): Interceptor {
        return Interceptor { chain ->
            val request = chain.request().newBuilder()
                .addHeader("Authorization", "Bearer token")
                .build()
            chain.proceed(request)
        }
    }
    
    @LoggingInterceptor
    @Provides
    fun provideLoggingInterceptor(): Interceptor {
        return HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        }
    }
    
    @Provides
    @Singleton
    fun provideOkHttpClient(
        @AuthInterceptor authInterceptor: Interceptor,
        @LoggingInterceptor loggingInterceptor: Interceptor
    ): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(authInterceptor)
            .addInterceptor(loggingInterceptor)
            .build()
    }
}

六、ViewModel注入 #

6.1 配置ViewModel #

kotlin
@HiltViewModel
class MainViewModel @Inject constructor(
    private val repository: UserRepository
) : ViewModel() {
    
    private val _users = MutableLiveData<List<User>>()
    val users: LiveData<List<User>> = _users
    
    fun loadUsers() {
        viewModelScope.launch {
            _users.value = repository.getUsers()
        }
    }
}

6.2 在Activity中使用 #

kotlin
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    
    private val viewModel: MainViewModel by viewModels()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        viewModel.users.observe(this) { users ->
            // 更新UI
        }
    }
}

6.3 在Fragment中使用 #

kotlin
@AndroidEntryPoint
class MainFragment : Fragment() {
    
    // 与Activity共享ViewModel
    private val sharedViewModel: MainViewModel by activityViewModels()
    
    // Fragment自己的ViewModel
    private val viewModel: DetailViewModel by viewModels()
}

七、预定义绑定 #

7.1 Application Context #

kotlin
class MyRepository @Inject constructor(
    @ApplicationContext private val context: Context
) {
    fun getResourceString(resId: Int): String {
        return context.getString(resId)
    }
}

7.2 Activity Context #

kotlin
class MyManager @Inject constructor(
    private val activity: Activity
) {
    // 使用Activity Context
}

八、测试 #

8.1 单元测试 #

kotlin
@HiltAndroidTest
class UserRepositoryTest {
    
    @get:Rule
    var hiltRule = HiltAndroidRule(this)
    
    @Inject
    lateinit var repository: UserRepository
    
    @Before
    fun init() {
        hiltRule.inject()
    }
    
    @Test
    fun testGetUsers() {
        val users = repository.getUsers()
        assertTrue(users.isNotEmpty())
    }
}

8.2 替换测试模块 #

kotlin
@Module
@InstallIn(SingletonComponent::class)
object TestNetworkModule {
    
    @Provides
    @Singleton
    fun provideFakeApiService(): ApiService {
        return FakeApiService()
    }
}

@UninstallModules(NetworkModule::class)
@HiltAndroidTest
class MainActivityTest {
    // 使用TestNetworkModule
}

九、最佳实践 #

9.1 模块组织 #

kotlin
// 按功能划分模块
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule

@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule

@Module
@InstallIn(SingletonComponent::class)
object RepositoryModule

9.2 使用接口 #

kotlin
interface UserRepository {
    fun getUsers(): List<User>
}

class UserRepositoryImpl @Inject constructor(
    private val apiService: ApiService
) : UserRepository {
    override fun getUsers(): List<User> {
        // 实现
    }
}

@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
    
    @Binds
    @Singleton
    abstract fun bindUserRepository(
        impl: UserRepositoryImpl
    ): UserRepository
}

十、总结 #

本章详细介绍了Hilt依赖注入:

  1. Hilt的基本概念和配置
  2. 依赖注入的基本使用
  3. 模块和依赖提供
  4. 组件与作用域
  5. 限定符的使用
  6. ViewModel注入
  7. 预定义绑定
  8. 测试配置
  9. 最佳实践

Hilt是Android推荐的依赖注入框架,可以大大简化依赖管理。

最后更新:2026-03-26