jeudi 18 mars 2021

Class instance based on input parameter using Guice binding

I have Java interface classes.

public interface ModelClient {
}

public interface DownstreamService1Client extends ModelClient {
   public ContentData getContentData();
}

public interface DownstreamService2Client extends ModelClient {
   public ContentData getContentData();
}

public interface DownstreamService3Client extends ModelClient {
   public ContentData getContentData();
}

I have another spec builder method:

ModelClientSpec<DownstreamService1Client> spec = ModelClientSpec.builder(DownstreamService1Client.class);

Above spec can be used to create a client:

DownstreamService1Client client = context.getResourceClient(spec);

which can be used to call downstream client to get data:

ContentData data = client.getContentData(); // get the data from downstream service.

I have created following client spec static map: "contentType" -> DownstreamClientSpec

"music" -> DownstreamClient1Spec
"books" -> DownstreamClient2Spec
...

Now I have a handler method:

public ContentData handle(String contentType) {

    // need to get a client based on contentType
    client = ???
    return  client.getContentData()
}

How do I get the client based on the contentType other than having the switch statement for contentType and specific client creation logic? Is it a clean way to dynamically bind the specific client using Guice?

Thanks!

Aucun commentaire:

Enregistrer un commentaire