Dagger2允许注入为空 [英] Dagger2 allow injection to be null
问题描述
因此,简而言之,同一款应用程序我有很多口味,但略有不同.我想为所有口味分别添加一个导航器.我正在使用Dagger2,并且每种口味都有一个子组件,在该组件中,我仅为给定口味注入东西.所以我也想注入一个Navigator类.
So, in short, I have a lot of flavors of the same app with slight differences. I would like to add a Navigator for all flavors independently. I'm using Dagger2, and I have a sub component for each flavor where I inject things only for a given flavor. So I would like to inject a Navigator class too.
诀窍是,通用代码中的某些类也使用此导航器,并带有null检查.因此,如果它为null,则很好,但如果不为空,则执行x.
The trick is, that some of the classes in the common code use this navigator too, with a null check. So if it's null, fine, but if not then do x.
所以我想要一个像这样的字段:
So I'd like to have a field like:
@Inject @Nullable Navigator navigator;
如果没有类似这样的@Provides方法,Dagger会给我一个错误,但这正是我想要的,我希望@Provides进入子模块,但仍要注入通用代码库中.
Dagger gives me an error if there is no @Provides method for something like this, but that's exactly what I want, I want the @Provides to go in the submodules but still inject in the common code base.
我该如何实现?
推荐答案
要支持可为空的类型,您只需在 @Provides
方法上添加 @Nullable
批注返回可为null的类型,Dagger将接受它.
To support a nullable type you just have to add a @Nullable
annotation on your @Provides
method that returns the nullable type and Dagger will accept it.
如果不这样做,Dagger会抱怨您只能从带有 @Nullable
注释的方法中提供可为空的类型.
If you don't, Dagger will complain that you can only provide nullable types from @Nullable
annotated methods.
这篇关于Dagger2允许注入为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!