栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Google Guice中实现“机器人腿”用例?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Google Guice中实现“机器人腿”用例?

如Guice
Wiki中所述
,您需要安装两个PrivateModule,每个都为您提供带有正确注释的Service。

public class MyModule extends AbstractModule {  @Override  protected void configure() {    install(new PrivateModule() {      @Override public void configure() {        // Bind Source to SourceDatabase.        bind(Source.class).to(SourceDatabase.class);        // Bind @Named("database") Service to Service.        bind(Service.class).annotatedWith(Names.named("database")) .to(Service.class);        // Now expose @Named("database") Service without exposing        // either of the other two conflicting bindings.        expose(Service.class).annotatedWith(Names.named("database"));      }    });    install(new PrivateModule() {      @Override public void configure() {        // Same as above.        bind(Source.class).to(SourceFileSystem.class);        bind(Service.class).annotatedWith(Names.named("file-system")) .to(Service.class);        expose(Service.class).annotatedWith(Names.named("file-system"));      }    });  }}

如果模块不是PrivateModule实例,则到Source和Service的那些绑定将相互冲突。但是,每个绑定取而代之的是从Injector继承所有公共绑定,而仅将In暴露

@Named(...)Service
给外部世界。这样,相同的
Service
实现可以注入相同的未注释
Source
但返回不同的完全注入类型。

另请注意,由于您尚未在任何非私有模块中建立绑定,因此您将无法在PrivateModules之外请求

Source
Service
(没有注释)。这应该是预期:该PrivateModule绑定不应该与任何公开的绑定冲突,并没有通过PrivateModule的暴露绑定一个进入,吉斯不知道哪个
Source
Service
返回。

最后,考虑到Module实例可以使用构造函数参数,将两个匿名内部PrivateModules提取为命名的等效项可能是一个好主意:

public class MyModule extends AbstractModule {  @Override  protected void configure() {    install(new SourcePrivateModule(SourceDatabase.class, "database"));    install(new SourcePrivateModule(SourceFileSystem.class, "file-system"));  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/496469.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号