简体   繁体   English

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

[英]how to create multiple instance of same type using google Guice

We have used Google Guice framework for dependency injection. 我们已经使用Google Guice框架进行依赖项注入。 I need to create multiple insatnce of an interface in java. 我需要在java中创建接口的多个insatnce。

The execution starts from here: KfhRecordValidator.java class in the below code: 执行从这里开始:下面代码中的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);
}}

The process class is having reference of RecordValidationHelper class and the injection is through constructor. 流程类具有RecordValidationHelper类的引用,而注入是通过构造函数进行的。 IRecordValidationService.java is an interface that is having validate method. IRecordValidationService.java是具有validate方法的接口。

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

class processor is having one method called process that is being called in RecordValidationHelper class. 类处理器具有一个称为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 extneds AbstractModule class of Guice injection that is having configure method. 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]));
        }

    } } }

SO the issue is if I am getting validation type as AVRO, JSON then it will bind IRecordValidationService to respective JsonValidationService/AvroSchemaValidationService class. 所以问题是如果我要获取验证类型为AVRO,JSON,则它将IRecordValidationService绑定到相应的JsonValidationService / AvroSchemaValidationService类。 I need to create multiple instance for that but it supports only once instance at a time. 我需要为此创建多个实例,但一次仅支持一个实例。 Below is the RecordValidationHelper.java class 下面是RecordValidationHelper.java类

public class RecordValidationHelper extends AbstractModule { private final IRecordValidationService recordValidationService; 公共类RecordValidationHelper扩展AbstractModule {私有最终IRecordValidationService recordValidationService;

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

public List processRecords(List requestRecords) { List records = new ArrayList<>(); public List processRecords(List requestRecords){列表记录= new 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;}

Anyone having any idea about how it should be implemented to get multiple instance suitable for this. 任何人都对如何实现它以获得适用于此的多个实例有任何想法。

Use @Named bindings 使用@Named绑定

In your DependencyModule , bind using names: 在您的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);

Then in your injectee: 然后在您的注射剂中:

@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;
}

See Guice's BindingAnnotation wiki page for more info. 有关更多信息,请参见Guice的BindingAnnotation Wiki页面

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

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