我如何创建一个模块,它有一个注解,比如@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。
这显示错误。
最佳答案
如果你想创建一个不同的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
作为 ApplicationComponent
的 @Subcomponent
:
@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);
}
}
注意从 @Module
注释中删除了 include
并且使用 @ApplicationContext
注释了 Context
创建JobManagerComponent
:
JobManagerComponent jobComponent = DaggerApplicationComponent.builder()
.applicationModule(applicationModule)
.build()
.provide(new JobManagerModule());
关于android - 具有不同范围的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40631236/