Dagger2 - 组件在应用程序中保持为静态对象
Dagger2 - Component hold as a static object in Application
在我的 Application
class 中,我将我的单例 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 class 中使用非静态访问器。
更广泛地说,你想要多少组件就有多少,但是如果组件提供@Singleton - 带注释的功能,组件的生命周期不应长于使用它的功能之一。
没关系。但是为什么要把它放在 Application
class 中呢?把它放在标准的单例 class 中,例如 Injector
。您仍然可能希望在 Application
中初始化该单例,这很好。
在我的 Application
class 中,我将我的单例 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 class 中使用非静态访问器。 更广泛地说,你想要多少组件就有多少,但是如果组件提供@Singleton - 带注释的功能,组件的生命周期不应长于使用它的功能之一。
没关系。但是为什么要把它放在 Application
class 中呢?把它放在标准的单例 class 中,例如 Injector
。您仍然可能希望在 Application
中初始化该单例,这很好。