如何使用Google Guice创建相同类型的多个实例

时间:2018-10-29 08:48:05

标签: java guice

我们已经使用Google Guice框架进行依赖项注入。我需要在Java中创建一个接口的多个实例。

从此处开始执行:下面代码中的KfhRecordValidator.java类:

public class KfhRecordValidator implements RequestHandler<Request, Response> {
       public Response handleRequest(Request request, Context context) 
        {
     // Resolve the necessary dependencies, and process the request.
       Injector injector = Guice.createInjector(new 
                      DependencyModule());
            Processor processor = 
                 injector.getInstance(Processor.class);
              return processor.process(request, context);
}}

进程类具有RecordValidationHelper类的引用,注入是通过构造函数进行的。 IRecordValidationService.java是具有validate方法的接口。

public interface IRecordValidationService {
              void validate(Record record) throws ValidationException;}

类处理器具有一个称为process的方法,该方法在RecordValidationHelper类中被调用。

class Processor {
   private final RecordValidationHelper recordValidationHelper;
@Inject
@SuppressWarnings({"WeakerAccess"})
public Processor(IRecordValidationService recordValidationService, 
IRecordService<ErrorRecord> recordService,
                 S3UtilsInterface s3Utils, IEnvironmentVariableReader 
                 environmentVariableReader) {
                 this.recordValidationHelper = new 
                 RecordValidationHelper(recordValidationService);
                 this.errorRecordHelper = new 
                 ErrorRecordHelper(recordService, environmentVariableReader);
}

public Response process(Request request, @SuppressWarnings("unused") Context context) {

    // Validate records
    List<LambdaRecord> records = recordValidationHelper.processRecords(request.getRecords());}

Class DependencyModule.java扩展了具有configure方法的Guice注入的AbstractModule类。

class DependencyModule extends AbstractModule {
@Override
protected void configure() {
    String validationType = System.getenv("ValidationType");

    validationType= validationType.toLowerCase(Locale.ENGLISH);

    String valType[]= validationType.split(",");
    int length= valType.length;

    for(int i=0;i<length;i++){

        switch(valType[i]){
         case "json":
             bind(IRecordValidationService.class).to(JsonValidationService.class);
             break;
         case "avro":
             bind(IRecordValidationService.class).to(AvroSchemaValidationService.class);
             break;
         case "clientlogging":
             bind(IRecordValidationService.class).to(ClientLoggingValidationService.class);
             break;
         case "servicelogs":
             bind(IRecordValidationService.class).to(ServiceLoggingValidationService.class);
             break;
         default:
             throw new UnsupportedOperationException(String.format("Encountered an unsupported ValidationType of '%s'.", valType[i]));
        }

    } } }

所以问题是,如果我要获取验证类型为AVRO,JSON,则它将IRecordValidationService绑定到相应的JsonValidationService / AvroSchemaValidationService类。我需要为此创建多个实例,但一次仅支持一个实例。 下面是RecordValidationHelper.java类

公共类RecordValidationHelper扩展AbstractModule {     私有最终IRecordValidationService recordValidationService;

@Inject
public RecordValidationHelper(IRecordValidationService recordValidationService) {
    this.recordValidationService = recordValidationService;
}

public List processRecords(List requestRecords){         列表记录=新的ArrayList <>();

    for (RequestRecord record : requestRecords) {
        try {

            Record domainRecord = new Record();
            domainRecord.setKey(record.getRecordId());
            domainRecord.setValue(new String(Base64.getDecoder().decode(record.getData())));

            // Use the injected logic to validate the record.
            ((IRecordValidationService) 
           recordValidationService).validate(domainRecord);}
           catch (ValidationException ex) {}}}
           return records;}

任何人都应该知道如何实现它以获取适合于此的多个实例。

1 个答案:

答案 0 :(得分:0)

使用@Named绑定

在您的DependencyModule中,使用名称进行绑定:

bind(IRecordValidationService.class)
  .annotatedWith(Names.named("json"))
  .to(JsonValidationService.class);
bind(IRecordValidationService.class)
  .annotatedWith(Names.named("avro"))
  .to(AvroSchemaValidationService.class);
bind(IRecordValidationService.class)
  .annotatedWith(Names.named("clientlogging"))
  .to(ClientLoggingValidationService.class);
bind(IRecordValidationService.class)
  .annotatedWith(Names.named("servicelogs"))
  .to(ServiceLoggingValidationService.class);

然后在注射剂中注射

@Inject
public RecordValidationHelper(
    @Named("json") IRecordValidationService jsonValidation,
    @Named("avro") IRecordValidationService avroValidation,
    @Named("clientlogging") IRecordValidationService clientLoggingValidation,
    @Named("servicelogs") IRecordValidationService serviceLogsValidation,
  ) {
    this.jsonValidation = jsonValidation;
    this.avroValidation = avroValidation;
    this.clientLoggingValidation = clientLoggingValidation;
    this.serviceLogsValidation = serviceLogsValidation;
}

有关更多信息,请参见Guice's BindingAnnotation wiki page