简体   繁体   中英

Dagger2 - Component hold as a static object in Application

In my Application class, I have my singleton Dagger Component as a static object and reach it via its static getter method.

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;
        }
}

What I want to know is that is this the right way to do this? Can it cause problems? If so, what are those?

It is ok, but you will not be able to use inject Context- dependent objects in that way. For component, requiring Context, use non - static accessor in Application class. Speaking more widely, there will be as many components as your want, but if if component provides @Singleton - annotated functionality, lifecycle of component should not be longer that one of feature using it.

It's okayish. But why would you put it in the Application class? Put it in standard singleton class called for example Injector . Still you might want to initialize that singleton in Application which is fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM