简体   繁体   中英

Guice - Multiple provider methods for same return types

In my module:

@Provides
@Singleton
public ExecutorService provideExecutorService(){
    return new ExecutorService(config);
}

In my class:

@Inject
private ExecutorService executorService;

Now, I need two instances of ExecutorService with a different config:

@Provides
@Singleton
public ExecutorService provideExecutorServiceA(){
    return new ExecutorService(configA);
}

@Provides
@Singleton
public ExecutorService provideExecutorServiceB(){
    return new ExecutorService(configB);
}

If I want to inject ExecutorService for the one created with configB in my class, how do I do it?

You can use 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);
}

The @Priority annotation looks like this :

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@BindingAnnotation
public @interface Priority
{
    Level value();

    public enum Level
    {
        LOW,
        HIGH
    }
}

Note that if you don't want to implement a custom annotation, wou can use the @Named annotation that is built-in Guice. You can then use it in your classes like this :

@Inject
public ReportingJob(@Priority(Priority.Level.LOW) ReportingDal dal)
{
    this.dal = dal;
}

EDIT

Or, if you are injecting via private field :

@Inject
@Priority(Priority.Level.LOW)
private ReportingDal dal;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM