[英]Dagger2 - Component hold as a static object in Application
在我的Application
类中,我将我的单例Dagger Component
作为静态对象,并通过其静态getter方法到达它。
public class MyApp extends Application {
private static UtilsComponent utilsComponent;
@Override
public void onCreate() {
......
}
public static UtilsComponent getUtilsComponent(){
if(utilsComponent == null){
utilsComponent = DaggerUtilsComponent.builder()
.formattersModule(new FormattersModule())
.build();
}
return utilsComponent;
}
}
我想知道的是这是正确的方法吗? 会引起问题吗? 如果是这样,那是什么?
可以,但是您将无法以这种方式使用注入上下文相关对象。 对于需要Context的组件,请在Application类中使用非静态访问器。 概括地说,将有您想要的组件数量,但是如果组件提供@Singleton-带注释的功能,则组件的生命周期不应比使用它的功能之一更长。
没关系。 但是为什么要把它放在Application
类中呢? 将其放在称为Injector
标准单例类中。 仍然您可能想要在Application
初始化该单例,这很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.