构建App Component时出现Unresolved reference DaggerApplicationComponent错误
Dagger未生成DaggerApplicationComponent的排查与解决
问题背景
使用Android Studio 2022.3.1 Patch 2构建项目时,Dagger无法自动生成DaggerApplicationComponent类,已尝试切换kapt依赖但问题依旧。相关代码如下:
MainApplication.kt
class MainApplication : Application() { val applicationComponent: ApplicationComponent = DaggerApplicationComponent.builder().applicationModule(ApplicationModule(this)).build() @Inject lateinit var indoor: Indoor override fun onCreate() { super.onCreate() applicationComponent.inject(this) } }
ApplicationComponent.kt
import dagger.Component import javax.inject.Singleton @Singleton @Component(modules = [ApplicationModule::class]) interface ApplicationComponent { @ApplicationContext fun context(): Context fun application(): Application fun inject(application: MainApplication) }
原build.gradle依赖配置
//Dagger implementation("com.google.dagger:dagger:2.48.1") implementation("com.google.dagger:dagger-android-support:2.48.1") annotationProcessor("com.google.dagger:dagger-android-processor:2.48.1") annotationProcessor("com.google.dagger:dagger-compiler:2.48.1")
ApplicationModule.kt
import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class ApplicationModule (private val application: Application) { @Provides @ApplicationContext fun provideContext(): Context = application @Provides fun provideApplication(): Application = application
排查与解决步骤
1. 修复Kotlin项目的注解处理器配置
Kotlin项目必须使用kapt而非annotationProcessor,且需先启用kapt插件:
- 在Module级build.gradle的plugins块中添加kapt插件:
plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' id 'kotlin-kapt' // 新增这一行 }
- 替换所有
annotationProcessor为kapt,确保版本统一:
//Dagger implementation("com.google.dagger:dagger:2.48.1") implementation("com.google.dagger:dagger-android-support:2.48.1") kapt("com.google.dagger:dagger-android-processor:2.48.1") kapt("com.google.dagger:dagger-compiler:2.48.1")
2. 补全缺失的@ApplicationContext限定符注解
@ApplicationContext并非Dagger自带注解,需自行定义:
import javax.inject.Qualifier import kotlin.annotation.AnnotationRetention.RUNTIME @Qualifier @Retention(RUNTIME) annotation class ApplicationContext
3. 修复ApplicationModule的语法错误
提供的ApplicationModule代码未闭合类定义,补全末尾的}:
import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class ApplicationModule (private val application: Application) { @Provides @ApplicationContext fun provideContext(): Context = application @Provides fun provideApplication(): Application = application } // 新增这一行
4. 清理缓存并重新构建项目
执行以下操作强制清理缓存并重新编译:
- 点击Android Studio顶部菜单栏
Build -> Clean Project - 随后点击
Build -> Rebuild Project - 或使用Gradle命令行:
./gradlew clean build
5. 检查注入目标类的合法性
确保Indoor类已被Dagger管理:
- 要么给
Indoor添加@Inject构造函数:
class Indoor @Inject constructor() { // ... }
- 要么在Module中提供
Indoor的Provider方法。
内容的提问来源于stack exchange,提问作者Heron Basquiat
相关产品推荐
相关产品推荐

