gpt4 book ai didi

java - 如何使用GinMapBinder

转载 作者:行者123 更新时间:2023-12-01 23:38:00 25 4
gpt4 key购买 nike

我们有一个项目,我们使用 GWT、MVP 范例和 Gin。我们有一位演示者,但现在我想要有不同的 View (一种用于普通用户,一种用于管理员,管理员看到的几乎相同,除了额外的列和不同的文本)。问题是我想选择在运行时使用的 View ,因为只有这样我才知道用户级别。

我找到了GinMapBinder ,这似乎是我想要的。代码中有一个关于如何实例化它的示例,但没有介绍如何使用它。

所以我的问题是:这是解决我的问题的方法吗?有人可以举一个例子来解释如何使用它以及如何在运行时选择不同的注入(inject)吗?

最佳答案

GinMapBinder允许您逐步构建到 java.util.Map 的绑定(bind),所以使用它的方法是获取 Map注入(inject)到你的对象中。您可以在 Guice's MapBinder javadoc 中找到完整的示例。 , GinMapBinder工作原理相同。

回答您的问题:

Is this the way to go and solve my problems?

它可以:如果你注入(inject) Map<String, Provider<MyView>>键是用户的角色。如果您只有两个这样的角色,您也只需注入(inject)两个 Provider s,并选择 get() 之一取决于用户的角色。 (另见下文)

但我不会这么做。我宁愿使用 deferred-binding 的组合(为普通用户和管理员用户生成不同的排列),使用属性提供者在运行时选择正确的排列,以及dynamic host page (在客户端启动之前将管理信息从服务器传递到客户端)。
您可以使用延迟绑定(bind)来选择要使用的 Ginjector(使用工厂<replace-with> 规则);除了 @GinModules 之外,Ginjectors 是相同的(相同的方法,从基本接口(interface)继承)。 ;因此你可以有一个 GinModule对于普通用户和另一个管理员用户,每个都绑定(bind) MyView.class到一个不同的实现类。

Can anybody give an example explaining how to use this and how to select the different injections at runtime?

构建绑定(bind)用户角色的映射来查看实现:

GinMapBinder<String, MyView> mapBinder =
GinMapBinder.newMapBinder(binder(), String.class, MyView.class);
mapBinder.addBinding("normal").to(MyViewImplNormal.class);
mapBinder.addBinding("admin").to(MyViewImplAdmin.class);

然后将其与用户角色一起注入(inject):

@Inject MyPresenter(@Named("user.role") String userRole,
Map<String, Provider<MyView>> views) {

并根据用户的角色选择适当的 View :

  // TODO: handle the case where the map has no value for the user role
this.view = views.get(userRole).get();

我正在谈论的替代方案:

bind(MyView.class).annotatedWith(named("user.normal")).to(MyViewImplNormal.class);
bind(MyView.class).annotatedWith(named("user.admin")).to(MyViewImplAdmin.class);



@Inject MyPresenter(@Named("user.isAdmin") boolean isAdmin,
@Named("user.normal") Provider<MyView> normalView,
@Named("user.admin") Provider<MyView> adminView) {

this.view = isAdmin ? adminView.get() : normalView.get();

关于java - 如何使用GinMapBinder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18350742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com