如何创建一个具有注释的模块,如@UserScope,依赖于另一个模块@Singleton?
@Module(includes = {ApplicationModule.class})
public class JobManagerModule
{
private static final String TAG = JobManagerModule.class.getSimpleName();
@UserScope
@Provides
public JobManager providesJobManager(final Context context)
{
Log.d(TAG, "Providing JobManager");
final Configuration configuration = new Configuration.Builder(context).build();
return new JobManager(configuration);
}
}
这里,JobManagerModule使用@UserScope提供,但ApplicationModule提供Context对象(JobManagerModule需要)作为@Singleton。
这显示错误。
答案 0 :(得分:3)
如果要创建不同的Scope
,则此范围必须是@Singleton
的子组件。
假设您ApplicationComponent
注明了@Singleton
:
@Singleton
@Component(
modules = ApplicationModule.class
)
public interface ApplicationComponent {
JobManagerComponent provide(JobManagerModule jobManagerModule);
}
ApplicationModule
提供Context
:
@Module
public class ApplicationModule {
protected final Application mApplication;
public ApplicationModule(Application application) {
mApplication = application;
}
@Provides
@ApplicationContext
public Context provideApplicationContext() {
return mApplication;
}
}
请注意,ApplicationComponent
必须提供JobManagerComponent
并且Context
提供了@ApplicationContext
注释。
现在,您将JobManagerComponent
创建为@Subcomponent
的{{1}}:
ApplicationComponent
@UserScope
@Subcomponent(
modules = JobManagerModule.class
)
public interface JobManagerComponent{
}
:
JobManagerModule
请注意从@Module
public class JobManagerModule
{
private static final String TAG = JobManagerModule.class.getSimpleName();
@UserScope
@Provides
public JobManager providesJobManager(@ApplicationContext Context context)
{
Log.d(TAG, "Providing JobManager");
final Configuration configuration = new Configuration.Builder(context).build();
return new JobManager(configuration);
}
}
注释中移除include
,并使用@Module
注释Context
创建@ApplicationContext
:
JobManagerComponent