已添加@Module仍触发@InstallIn需搭配@Module/EntryPoint的Hilt错误求助
问题
编译Hilt时触发错误:
@InstallIn-annotated classes must also be annotated with @Module or @EntryPoint: com.example.newsapp.di.AppModule
[Hilt] Processing did not complete. See error above for details.
代码与参考教程完全一致,但教程代码可正常运行,自身代码报错,代码如下:
@Module @InstallIn(SingletonComponent::class) object AppModule { @Provides fun baseURL() = BASE_URL @Provides fun logging() = HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY) @Provides fun okHttpClient() = okhttp3.OkHttpClient.Builder() .addInterceptor(logging()) .build() @Provides @Singleton fun provideRetrofit(baseUrl: String): NewsService = Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient()) .build() .create(NewsService::class.java)}
解决方案
逐一排查以下项:
- 对齐Hilt依赖版本:确认项目中Hilt相关依赖版本与教程完全一致,不同版本的注解处理器逻辑可能存在差异。
- 清理缓存后重新编译:执行
./gradlew clean build,或在Android Studio中通过Build -> Clean Project -> Rebuild Project操作,缓存异常可能导致注解识别失败。 - 校验注解导入包:确保
@Module、@InstallIn、SingletonComponent均来自Hilt官方包:import dagger.hilt.InstallIn import dagger.hilt.android.components.SingletonComponent import dagger.hilt.Module - 检查Application类配置:确认自定义Application类已添加
@HiltAndroidApp注解,这是Hilt初始化的必要条件:@HiltAndroidApp class MyApplication : Application() { // ... } - 确认模块访问权限:保证AppModule的访问修饰符为public(Kotlin中object默认public,无需额外设置),避免权限限制导致处理器无法识别。
内容的提问来源于stack exchange,提问作者Fary
相关产品推荐
相关产品推荐

