简体   繁体   English

Guice-相同返回类型的多个提供程序方法

[英]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: 现在,我需要两个具有不同配置的ExecutorService实例:

@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? 如果我想为班上用configB创建的ExecutorService注入ExecutorService,我该怎么做?

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 : @Priority批注如下所示:

@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. 请注意,如果您不想实现自定义注释,则可以使用内置Guice的@Named注释 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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