如果您要創建不同的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
註釋和Context
與@ApplicationContext
創作註釋去除:
JobManagerComponent jobComponent = DaggerApplicationComponent.builder()
.applicationModule(applicationModule)
.build()
.provide(new JobManagerModule());
這已解決了問題,但它在其他地方引發了衝突。我會發表另一個問題。 – Subby
我問過這個問題http://stackoverflow.com/questions/40632408/two-injects-in-one-object-but-from-two-different-components – Subby
任何想法如何我可以將JobManager注入到MyObject以及來自不同組件的不同對象? – Subby