Hilt는 Dependency Injection을 제공하는 라이브러리다.
- binding: hilt에서 관리하는 객체, spring의 bean에 대응된다.
hilt 등록
// AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:name=".GlobalApplication">
...
// build.gradle.kts (project)
plugins {
...
id("com.google.gms.google-services") version "4.4.3" apply false
id("com.google.dagger.hilt.android") version "2.57.1" apply false
}
// build.gradle.kts (app)
...
plugins {
...
id("com.google.dagger.hilt.android")
kotlin("kapt")
}
dependencies {
implementation("com.google.dagger:hilt-android:2.57.1")
kapt("com.google.dagger:hilt-compiler:2.57.1")
}
@HiltAndroidApp
class GlobalApplication: Application() {
override fun onCreate() {
super.onCreate()
}
}
Binding을 생성
@Module // Hilt에게 이 class를 알려줌
@InstallIn(SingletonComponent::class) // binding의 Scope를 지정
abstract class RepositoryModule {
@Binds // 구현체와 interface를 연결해줌
abstract fun bindFollowRepository(
impl: FollowRepositoryImpl
): FollowRepository
}
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides // binding 객체를 생성하는 메서드라는 걸 알림
@Singleton // 객체의 단일을 보장
@Named("NonAuthed") //
fun provideNonAuthedClient(
userAgentInterceptor: UserAgentInterceptor // 의존성 주입
): OkHttpClient {
return OkHttpClient.Builder()
...
.build()
}
의존성 주입 받기
// binding 객체에서 주입 받기
class FollowRepositoryImpl @Inject constructor(
val followApiService: FollowApiService // 의존성을 주입 받음
): FollowRepository {
}
// activity에서 주입 받기
@AndroidEntryPoint
class FollowListActivity: AppCompatActivity() {
@Inject
lateinit var repository: FollowRepository // Hilt가 주입
}