How to use dagger in a android library project

后端 未结 3 1048
梦如初夏
梦如初夏 2020-12-08 00:23

I\'m currently trying to add Dagger to my android projects. For the apps projects its easy and clear to me, how to build the ObjectGraph. But I dont quite know whats the bes

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 00:55

    In case someone using Dagger 2 gets here, this is the way I've done in my App:

    In the library module I've created the following Module and Component:

    @Module
    public class ModuleUtil {
    
        @Provides
        public RestTemplate provideRestTemplate() {
            return new RestTemplate();
        }
    
    }
    
    @Singleton
    @Component(
            modules = {
                    ModuleUtil.class
            })
    public interface MainComponent {
        void inject(Postman postman);
    }
    

    And then I've created the Singleton below in order to manage the injections:

    public class DaggerWrapper {
    
        private static MainComponent mComponent;
    
        public static MainComponent getComponent() {
            if (mComponent == null) {
                initComponent();
            }
            return mComponent;
        }
    
        private static void initComponent () {
           mComponent = DaggerMainComponent
                    .builder()
                    .utilModule(new ModuleUtil())
                    .build();
        }
    }
    

    When some class from the library module needs to inject its members, I simply call DaggerWrapper.getComponent().inject(this); and that't it.

提交回复
热议问题