【问题标题】:how to achieve dynamic binding in Google-Guice?如何在 Google-Guice 中实现动态绑定?
【发布时间】:2011-12-01 14:13:05
【问题描述】:

我正在尝试在服务中实现服务外观以支持向后兼容性。

但是,我在 Guise 动态绑定中遇到了问题。我需要根据客户端应用程序请求的版本绑定相应的实现类。

有人知道如何在 Google-Guice 中实现动态绑定吗?

【问题讨论】:

标签: java guice restlet-2.0


【解决方案1】:

你可以绑定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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 2022-09-10
    相关资源
    最近更新 更多