在我的模块中:
@Provides
@Singleton
public ExecutorService provideExecutorService(){
return new ExecutorService(config);
}
在我班上:
@Inject
private ExecutorService executorService;
现在,我需要两个具有不同配置的ExecutorService实例:
@Provides
@Singleton
public ExecutorService provideExecutorServiceA(){
return new ExecutorService(configA);
}
@Provides
@Singleton
public ExecutorService provideExecutorServiceB(){
return new ExecutorService(configB);
}
如果我想为我的课程中使用configB创建的ExecutorService注入,我该怎么做?
答案 0 :(得分:5)
您可以使用binding annotations:
@Provides
@Singleton
@Priority(Priority.Level.HIGH)
public static ReportingDal createHighPriorityReportingDal(DataSource dataSource,
DatabaseType databaseType,
ReportingQueryGenerator queryGenerator)
{
return new ReportingDalImpl(dataSource, databaseType, Queue.DEFAULT, queryGenerator);
}
@Provides
@Singleton
@Priority(Priority.Level.LOW)
public static ReportingDal createLowPriorityReportingDal(DataSource dataSource,
DatabaseType databaseType,
ReportingQueryGenerator queryGenerator)
{
return new ReportingDalImpl(dataSource, databaseType, Queue.MAINTENANCE, queryGenerator);
}
@Priority注释如下所示:
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@BindingAnnotation
public @interface Priority
{
Level value();
public enum Level
{
LOW,
HIGH
}
}
请注意,如果您不想实现自定义注释,则可以使用内置Guice的@Named annotation。然后,您可以在类中使用它:
@Inject
public ReportingJob(@Priority(Priority.Level.LOW) ReportingDal dal)
{
this.dal = dal;
}
修改强>
或者,如果您通过私人领域注入:
@Inject
@Priority(Priority.Level.LOW)
private ReportingDal dal;