- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我们有一个项目,我们使用 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/
我是一名优秀的程序员,十分优秀!