2011-12-01 71 views
1

我正在嘗試將服務外觀實現到服務中以支持向後兼容性。如何在Google-Guice中實現動態綁定?

但是,我正面臨着Guise動態綁定的問題。我需要根據客戶端應用程序請求的版本來綁定相應的實現者類。

有沒有人有想法如何在谷歌Guice中實現動態綁定?

+0

我昨天回答了一個非常類似的問題: http://stackoverflow.com/questions/8257863/guice-change-binding-by-property-string-in-external-text-file-on-runtime/ 8319512#8319512 – eiden

回答

2

您可以結合annotations去:

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

,並有這樣的代碼:

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

或者你可以使用multibindings

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

,然後你使用它像這樣:

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