본문 바로가기

Android

Android Dagger Hilt

주의

이 블로그는 개인적인 생각과 이해를 정리한 곳입니다. 실제와 다를 수 있으니 글에서 참고한 글을 꼭 확인해주세요.

요약

  • Hilt는 Dagger를 기반으로 만들어진 Android Dependency Injection 라이브러리이다.
  • Hilt는 Dagger에서 어려움과 불편함이 많았던 Activity와 Fragment의 생성자 Injection을 쉽게 사용할 수 있도록 지원한다.
  • Dagger, Dagger-Android와 비교할 수 없을 정도로 사용방법이 아주 간단하다. Dagger에 대해서 잘 몰라도 사용할 수 있다.

Hilt란?

Hilt는 Dagger를 기반으로 만들어진 Android Dependency Injection 라이브러리로, Google에서 만들고 관리하고 있다.

 

Dagger, Dagger-Android에서는 Component 선언과 Activity, Fragment에 Inject를 시키는 상용구 코드들이 상당히 많았는데, Hilt는 이를 모두 제거시켜준다. Hilt는 AnnotationProcessing단계에서 기존에 필요했던 Componenet 선언과 Activity, Fragment에 Inject를 시키는 코드들을 직접 생성해준다.

Hilt Annotation

Hilt는 Dagger를 기반으로 되어있기 때문에 사용법이 거의 동일하지만 Android를 대상으로 이미 만들어져 있는 Annotation들이 존재한다.

@HiltAndroidApp

안드로이드 Application 클래스 선언부에 붙여주어야 하는 Annotation이다. 이 Annotation을 중심으로 DI 그래프를 그리고 관리한다.

 

@HiltAndroidApp
class TestApplication: Application() {
}

@AndroidEntryPoint

안드로이드에서 일반적으로 사용되는 Inject의 진입점(?)이 되는 클래스들의 선언부에 붙여주어야 하는 Annotation이다. 예를 들면 Activity, Fragment, View, Service가 있다. @AndroidEntryPoint Annotation을 붙여주지 않을 경우 Hilt에서는 해당 필드 Inject가 불가능하다는 에러를 발생시켜준다. Activity에서 필요한 Inject가 없다고 하더라도 Activity에서 사용하는 Fragment에 Inject가 있다면 Activity에도 꼭 이 Annotation을 붙여주어야 한다.

@AndroidEntryPoint
class TestActivity: AppCompatActivity() {
}

@AndroidEntryPoint
class TestFragment: Fragment() {
}

Component와 Scope

Dagger, Dagger-Android에서는 Activity, Fragment 별 Component와 Scope를 직접 선언하고 이를 사용했었지만, Hilt에서는 기본적으로 제공해준다. 제공해주고 있는 Component와 Scope는 아래와 같다.

Component

  • ApplicationComponent
  • ActivityRetainedComponent​
  • ActivityComponent
  • FragmentComponent
  • ViewComponent
  • ViewWithFragmentComponent
  • ServiceComponent

Scope

  • @Singleton (Java 제공)
  • @ActivityRetainScope
  • @ActivityScoped
  • @FragmentScoped
  • @ViewScoped
  • @ServiceScoped
@InstallIn(AcitivtyComponent::class)
@Module
class TestActivityModule {
    
    @Provides
    @ActivityScoped
    fun provideNumber(): Int = 0
}

@InstallIn(FragmentComponent::class)
@Module
class TestFragmentModule {
    
    @Provides
    @FragmentScoped
    fun provideString(): String = "test"
}

 

 

@Inject

@Module

@InstallIn

@Provides

@Binds

@Qualifier

의존성 추가

Project build.gradle

buildscript {
    ...
    dependencies {
        ...
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
    }
}

App build.gradle

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

android {
  ...
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

dependencies {
    implementation "com.google.dagger:hilt-android:2.28-alpha"
    kapt "com.google.dagger:hilt-android-compiler:2.28-alpha"
}

참고

'Android' 카테고리의 다른 글

안드로이드 Compose: 선언적 UI 개발의 미래  (0) 2023.09.16
Android Activity - Lifecycle(생명주기)  (0) 2020.09.25
Android Jetpack ViewModel  (0) 2020.09.22
Android LiveData  (0) 2020.09.09