@Inject带有参数的构造函数

时间:2019-11-10 03:56:34

标签: dagger-2

我看到了将@inject注释与参数构造函数一起使用的方法。我在项目的所有部分的@module中都没有用。我不明白这段代码是如何在构造函数中注入或提供参数的。

您能帮我分析一下吗? 数据管理器在哪里提供?

在整个项目中,@module + @provide不用于提供数据管理器。我只知道@inject只能注释无参数的构造函数。我不知道在哪里实例化无参数数据管理器对象。谢谢您的帮助

应用程序:

 public class Scallop extends Application {
        private ApplicationComponent applicationComponent;

        @Override
        public void onCreate() {
            super.onCreate();
            applicationComponent = DaggerApplicationComponent.builder()
                    .applicationModule(new ApplicationModule(this))
                    .build();
        }

        public ApplicationComponent getApplicationComponent() { 
            return applicationComponent;
        }
    }

应用程序模块:

    @Module
    public class ApplicationModule {
        private Scallop application;

        public ApplicationModule(Scallop application) { // 提供类的构造器,传入Applicaton
            this.application = application;
        }

        @Provides
        @Singleton
        Application provideApplication() { 
            return application;
        }

        @Provides
        @ApplicationContext
        Context provideContext() { 
            return application;
        }

        @Provides
        @Singleton
        Retrofit provideRetrofit() {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(Constants.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            return retrofit;
        }

        @Provides
        @Singleton
        GankIOService provideGankIOService(Retrofit retrofit) { 
            return retrofit.create(GankIOService.class);
        }
    }

    @Singleton
    @Component(modules = ApplicationModule.class)
    public interface ApplicationComponent {
        Application getApplication();  

        DataManager getDataManager();
    }
```

一个班级:

   @Singleton
    public class DataManager {
        private GankIOService gankIOService;
        private PreferencesHelper preferencesHelper;

        @Inject
        public DataManager(GankIOService gankIOService, PreferencesHelper preferencesHelper) {
            this.gankIOService = gankIOService;
            this.preferencesHelper = preferencesHelper;
        }
    }

片段模块:

    @FragmentScope
    @Component(modules = FragmentModule.class, dependencies = ApplicationComponent.class)
    public interface FragmentComponent {  
        void inject(HomeFragment homeFragment);

        void inject(GanHuoPageFragment pageFragment);

        void inject(XianDuFragment xianDuFragment);

        void inject(XianDuPageFragment xianDuPageFragment);

        void inject(PicturesFragment picturesFragment);

        void inject(MoreFragment moreFragment);
    }

    @FragmentScope
    @Documented
    @Scope
    @Retention(value = RetentionPolicy.RUNTIME)
    public @interface FragmentScope {
    }

   ``` 

此处无法理解参数为@inject的构造函数

     public class GanHuoPagePresenter extends BasePresenter<GanHuoPageContract.View>
            implements GanHuoPageContract.Presenter {
        private DataManager dataManager;
        private Disposable disposable;

        @Inject
        public GanHuoPagePresenter(DataManager dataManager) { // here here
            this.dataManager = dataManager;
        }

        @Override
        public void detachView() {
            super.detachView();
            if (disposable != null) {
                disposable.dispose();
            }
        }

        @Override
        public void getGanHuo(String category, final int page) {
            final List<GanHuo> ganHuoList = new ArrayList<>();
            Observable<BaseResponse<GanHuo>> observable = dataManager.getGanHuo(category, page);
            disposable = observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .concatMap(new Function<BaseResponse<GanHuo>, ObservableSource<GanHuo>>() {
                @Override
                public ObservableSource<GanHuo> apply(@NonNull BaseResponse<GanHuo> ganHuoBaseResponse)
                        throws Exception {
                    return Observable.fromIterable(ganHuoBaseResponse.getResults());
                }
            }).filter(new Predicate<GanHuo>() {
                @Override
                public boolean test(@NonNull GanHuo ganHuo) throws Exception {
                    return !ganHuo.getType().equals("福利");
                }
            }).subscribe(new Consumer<GanHuo>() {
                @Override
                public void accept(GanHuo ganHuo) throws Exception {
                    ganHuoList.add(ganHuo);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    getView().showError(throwable.getMessage());
                }
            }, new Action() {
                @Override`enter code here`
                public void run() throws Exception {
                    getView().showList(ganHuoList, page);
                }
            });
        }
    }

这是在MVP模式下在V中使用的方式:

@Inject GanHuoPagePresenter presenter

2 个答案:

答案 0 :(得分:0)

那就是constructor injection。通过使用@Inject标记构造函数,Dagger知道了该对象,并可以在需要时创建它。不需要模块,例如以下是创建某些Foo的有效Dagger设置。

public class Foo {
    @Inject
    public Foo() {}
}

@Component
interface MyComponent {
    Foo getFoo();
}

答案 1 :(得分:0)

@Inject只能注释无参数构造函数是不正确的。来自documentation

  

可注入的构造函数带有@Inject注释,并接受零个或多个依赖项作为参数。

我在Github上找到了“您的”项目,所以让我们看看GanHuoPagePresenter的依赖项来自哪里。

@Inject
public GanHuoPagePresenter(DataManager dataManager) {
    this.dataManager = dataManager;
}

@Inject
public DataManager(GankIOService gankIOService,PreferencesHelper preferencesHelper){
// gankIOService is provided by ApplicationModule and preferencesHelper uses constructor injection
    this.gankIOService = gankIOService;
    this.preferencesHelper = preferencesHelper;
}

@Inject
public PreferencesHelper(@ApplicationContext Context context){
// context is provided again by ApplicationModule
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}