Dagger注入SPManager报错:lateinit属性未初始化,求解决方案
解决Dagger注入SPManager未初始化问题
问题根源
你仅在HomeFragment中给spManager标注了@Inject注解,但未触发Dagger的注入流程,导致变量始终处于未初始化状态。
具体解决步骤
1. 触发Fragment注入
在Fragment的生命周期方法中执行注入操作,推荐在onAttach或onCreateView中完成:
- 若使用Dagger Android(集成了
dagger-android依赖),直接调用官方注入方法:
override fun onAttach(context: Context) { AndroidInjection.inject(this) super.onAttach(context) }
- 若手动管理Dagger组件,从Application中获取Component实例完成注入:
override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // 假设你的Application类为MyApplication,持有AppComponent实例 (requireActivity().application as MyApplication).appComponent.inject(this) binding = FragmentHomeBinding.inflate(inflater, container, false) return binding.root }
2. 确保SPManager可被Dagger提供
检查SPManager的依赖配置,二选一即可:
- 给
SPManager添加@Inject构造函数(需传入Context依赖):
class SPManager @Inject constructor(private val context: Context) { // SharedPreference操作逻辑 fun getProductID(): String { // 实现代码 } fun saveProductID(id: Long) { // 实现代码 } }
- 在Dagger Module中提供
SPManager实例:
@Module class AppModule { @Provides fun provideSPManager(context: Context): SPManager { return SPManager(context) } }
3. 配置Component注入方法
在你的Dagger Component接口中,添加针对HomeFragment的注入方法:
@Component(modules = [AppModule::class]) interface AppComponent { fun inject(fragment: HomeFragment) }
4. 确认注入时机
保证注入操作在调用spManager之前完成,你的getUserList在onViewCreated中执行,只要注入在onViewCreated之前触发即可。
内容的提问来源于stack exchange,提问作者Inveniuum
相关产品推荐
相关产品推荐

