IT/Android
🧩 5분 만에 이해하는 Hilt 애노테이션
왕귀
2025. 5. 24. 23:03
728x90
반응형
✨ 5분 만에 이해하는 Hilt 애노테이션
Hilt는 Android에서 수동 의존성 주입의 보일러플레이트를 줄여주는 라이브러리입니다. 이 가이드는 Android 프로젝트에서 자주 사용되는 Hilt 애노테이션과 예제 코드를 소개합니다.
@HiltAndroidApp
Application 클래스에 적용하여 Hilt를 초기화하고, 앱 전체에 DI 컨테이너를 제공합니다.
@HiltAndroidApp
class SampleApplication : Application()
AndroidManifest.xml에 이 Application 클래스를 등록해야 Hilt가 초기화됩니다.
@AndroidEntryPoint
Activity, Fragment, Service 등에 의존성을 주입하려면 이 애노테이션이 필요합니다.
Fragment에 적용했다면, 이를 포함하는 Activity에도 @AndroidEntryPoint를 붙여야 합니다.
@Inject
생성자 또는 필드에 주입할 대상을 표시합니다.
▶ 생성자 주입
class MainRepository @Inject constructor()
▶ 필드 주입
@Inject lateinit var mainRepository: MainRepository
주의: 필드가 private이면 Hilt가 주입할 수 없습니다.
@Module + @InstallIn
생성자 주입이 불가능한 경우, @Module을 사용해 Hilt에 의존성을 제공하는 방법을 정의합니다.
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
fun provideRetrofit(): Retrofit {
return Retrofit.Builder().baseUrl(BASE_URL).build()
}
}
@Binds vs @Provides
@Binds
는 인터페이스 구현체를 바인딩할 때,@Provides
는 직접 생성 로직을 제공할 때 사용됩니다.
// Binds
@Binds
abstract fun bindRepo(impl: RepoImpl): Repo
// Provides
@Provides
fun provideApi(): Api = ApiImpl()
@Qualifier
같은 타입의 여러 인스턴스를 구분할 때 사용합니다.
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class LoggingInterceptor
Scope 애노테이션
기본적으로 Hilt의 바인딩은 스코프가 지정되지 않아서 매번 새로운 인스턴스를 생성합니다. 특정 컴포넌트 수명 주기에 따라 동일한 인스턴스를 공유하려면 스코프를 지정해야 합니다.
예: @Singleton
은 애플리케이션 전역에서 단일 인스턴스를 유지합니다.
Component | Scope | Created | Destroyed |
---|---|---|---|
SingletonComponent | @Singleton | Application#onCreate() | Application shutdown |
ActivityRetainedComponent | @activityRetainedScope | Activity#onCreate() | Activity#onDestroy() (permanent) |
ActivityComponent | @ActivityScoped | Activity#onCreate() | Activity#onDestroy() |
ViewModelComponent | @ViewModelScoped | ViewModel constructor | ViewModel cleared |
FragmentComponent | @FragmentScoped | Fragment#onAttach() | Fragment#onDetach() |
ViewComponent | @ViewScoped | View creation | View destroy |
ServiceComponent | @ServiceScoped | Service#onCreate() | Service#onDestroy() |
@EntryPoint
Adapter, ContentProvider 등 Android 구성요소가 아닌 클래스에서 주입받을 때 사용합니다.
@EntryPoint
@InstallIn(SingletonComponent::class)
interface MyEntryPoint {
fun getRepository(): Repository
}
@AssistedInject
런타임에 파라미터가 필요한 경우 사용합니다.
1. ViewModel 클래스에 적용
class MainViewModel @AssistedInject constructor(
@Assisted val userId: String,
private val repo: UserRepository
) : ViewModel()
2. Factory 생성
@AssistedFactory
interface MainViewModelFactory {
fun create(userId: String): MainViewModel
}
3. Activity/Fragment에서 사용
val viewModel = factory.create(userId)
📙 출처
728x90
반응형