我正在从许多来源研究Dagger 2,例如:http://fernandocejas.com/2015/04/11/tasting-dagger-2-on-android/
但我仍未找到问题的答案.
我在一个非常复杂的应用程序上工作,其中包含数十个片段和一些我想使用DI的活动(匕首2).对于所有这些片段和活动,我都有一个BaseActivity和一个BaseFragment.但是,就我阅读和尝试而言,为了在我的MainActivity中使用@Inject,我必须在Component接口中指定它,还必须在onCreate方法中调用getApplicationComponent().inject(this).当我仅针对BaseActivity执行此 *** 作时,不会在MainActivity中注入@Inject带注释的字段.更糟糕的是,直到执行该代码的特定部分并抛出NPE时,我才发现这一点.
到目前为止,这对我来说是一个大难题,因为这可能是许多崩溃的原因.我将需要在Component接口中指定数十个片段和活动,并且不要忘记在每个onCreate方法中调用inject.
我很高兴听到任何解决方案,因为我真的很想使用DI.
代码示例:
@Singleton@Component(modules = ApplicationModule.class)public interface ApplicationComponent { voID inject(BaseActivity baseActivity); Analytics analytics();}public class BaseActivity extends AppCompatActivity { @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getApplicationComponent().inject(this); }}public class MainActivity extends BaseActivity { @Inject Analytics analytics; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); analytics.log("event1"); // THROWS NPE! }}
解决方法:
您不能通过注入父类在子类中注入属性(因为dagger2在编译时起作用,并且无法动态检查子类中带注释的属性.)
您可以将分析向上移动到超级,然后将其注入到那里.要在子类中注入带注释的字段,您将不得不在此处再次调用注入.
您可以在基类中创建一个抽象方法,例如只需在其中处理注入的inject(App app).这样,您就不会“错过”它.
如官方documentation所述:
总结While a members-injection method for a type will accept instances of its subtypes, only Inject-annotated members of the parameter type and its supertypes will be injected; members of subtypes will not.
以上是内存溢出为你收集整理的匕首2-如何仅注入基本活动/片段全部内容,希望文章能够帮你解决匕首2-如何仅注入基本活动/片段所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)