有可能在模块中注入东西吗?
我有2个基本模块/组件:
@Component(modules = {OkHttpModule.class}) public interface OkHttpComponent extends AppComponent { OkHttpClient provideOkHttpClient(); } @Module public class OkHttpModule { @Provides OkHttpClient provideOkHttpClient() { return mHttpClient; } }
@Component(modules = {GsonModule.class}) public interface GsonComponent extends AppComponent { Gson provideGson(); } @Module public class GsonModule { @Provides Gson provideGson() { return mGson; } }
有了这个模块/组件,我想创建一个第3个模块:
@Component(dependencies = {OkHttpComponent.class,GsonComponent.class},modules = {RetrofitModule.class}) public interface RetrofitComponent extends AppComponent { API provideAPI(); } @Module public class RetrofitModule { @Inject OkHttpClient mHttpClient; @Inject Gson mGson; @Provides VeentsMeAPI provideVeentsMeAPI() { return mVeentsMeAPI; } }
但是mHttpClient和mGson没有被注入.有可能在模块中注入东西吗?如果是,如何?
我创建了这样的组件:
okHttpComponent = DaggerOkHttpComponent.builder() .okHttpModule(new OkHttpModule(this)) .build(); gsonComponent = DaggerGsonComponent.builder() .gsonModule(new GsonModule()) .build(); retrofitComponent = DaggerRetrofitComponent.builder() .retrofitModule(new RetrofitModule()) .okHttpComponent(okHttpComponent) .gsonComponent(gsonComponent) .build();
解决方法
在我看来,注入模块并不重要.根据模块的Dagger1定义,所有模块都被声明为complete = false,library = true,这意味着只要包含不在您使用的组件中的模块,您就不需要指定任何真正的魔法,或使您的组件依赖关系彼此链接,使您可以注入的每个依赖项仅在一个组件中指定.
您将在构造函数参数中获取其他模块的依赖关系.您需要将模块包含在包含列表中,或者您需要在组件中指定的模块位于同一范围内.
正确的方法是这样做:
@Module public class OkHttpModule { @Provides @ApplicationScope public OkHttpClient okHttpClient() { return new OkHttpClient(); } } @Module public class GsonModule { @Provides @ApplicationScope public Gson gson() { return new Gson(); } } @Module(includes={GsonModule.class,OkHttpModule.class}) //look closely,this is the magic public class RetrofitModule { @Provides @ApplicationScope public VeentsMeAPI veentsMeAPI(Gson gson,OkHttpClient okHttpClient) { //dependencies! return RestAdapter.Builder() .setClient(new Client(okHttpClient)) .setConverter(new GsonConverter(gson)) .create(VeentsMeAPI.class); } }
然后就是
@Scope @Retention(RetentionPolicy.RUNTIME) public @interface ApplicationScope {}
然后
@ApplicationScope @Component(modules={RetrofitModule.class}) //contains all other modules/dependencies public interface AppComponent { OkHttpClient okHttpClient(); Gson gson(); VeentsMeAPI veentsMeAPI(); void inject(Something something); }
和
那么你会得到生成的东西,你必须一起构建它
AppComponent appComponent = DaggerAppComponent.create(); //use appComponent.inject(stuff); with `void inject(Stuff stuff);` methods defined in AppComponent
组件依赖关系与子组件相同,因此这些依赖关系与子组件相同,因此它们不适用于从相同范围继承依赖关系.相同范围的依赖关系应该在同一个组件中,只是不同的模块.