Pankaj Rastogi
Pankaj Rastogi

Reputation: 61

how to achieve dynamic binding in Google-Guice?

I am trying to implement service façade into services to support backward compatibility.

However, I am facing problem in Guise dynamic binding. I need to bind respective implementer class depending upon the version requested by client applications.

Does anyone having idea how to achieve dynamic binding in Google-Guice?

Upvotes: 1

Views: 1716

Answers (1)

Geno Roupsky
Geno Roupsky

Reputation: 646

You can go with binding annotations:

bind(Facade.class).annotatedWith(VersionOne.class).to(OldFacade.class);
bind(Facade.class).annotatedWith(VersionTwo.class).to(NewFacade.class);

and have code like:

@Inject @VersionOne Facade oldFacade;
@Inject @VersionTwo Facade newFacade;
if (version == 1)
    return oldFacade
else
    return newFacade;

Or you can use multibindings:

MapBinder<Integer, Facade> mapBinder = MapBinder.newMapBinder(binder(), Integer.class, Facade.class);
mapBinder.addBinding(1).to(OldFacade.class);
mapBinder.addBinding(2).to(NewFacade.class);

and then you use it like so:

@Inject Map<Integer, Facade> facadeMap;
return facadeMap.get(version);

Upvotes: 2

Related Questions