国家网站icp备案查询wordpress关闭新闻活动模块
web/
2025/10/4 10:21:35/
文章来源:
国家网站icp备案查询,wordpress关闭新闻活动模块,云服务器可以用来做网站么,怎么做网站免费的如果接口有多个实现#xff0c;则Google guice提供了一种精巧的方法来选择目标实现。 我的示例基于Josh Long #xff08; starbuxman #xff09;的出色文章#xff0c;内容涉及Spring提供的类似机制。 因此#xff0c;请考虑一个名为MarketPlace的接口#xff0c;该接… 如果接口有多个实现则Google guice提供了一种精巧的方法来选择目标实现。 我的示例基于Josh Long starbuxman 的出色文章内容涉及Spring提供的类似机制。 因此请考虑一个名为MarketPlace的接口该接口具有两个实现分别是AndroidMarketPlace和AppleMarketPlace interface MarketPlace {
}class AppleMarketPlace implements MarketPlace {Overridepublic String toString() {return apple;}
}class GoogleMarketPlace implements MarketPlace {Overridepublic String toString() {return android;}
} 并考虑以下实现的用户 class MarketPlaceUser {private final MarketPlace marketPlace;public MarketPlaceUser(MarketPlace marketPlace) {System.out.println(MarketPlaceUser constructor called..);this.marketPlace marketPlace;}public String showMarketPlace() {return this.marketPlace.toString();}} MarketPlaceUser消除这些实现歧义的一种好方法是使用一种称为绑定注释的guice功能。 要利用此功能请首先通过以下方式为每个实现定义注释 Retention(RetentionPolicy.RUNTIME)
Target({ElementType.FIELD, ElementType.PARAMETER})
BindingAnnotation
interface Android {}Retention(RetentionPolicy.RUNTIME)
Target({ElementType.FIELD, ElementType.PARAMETER})
BindingAnnotation
interface Ios {} 并将这些注释以及与该注释相对应的适当实现告知Guice活页夹 class MultipleInstancesModule extends AbstractModule {Overrideprotected void configure() {bind(MarketPlace.class).annotatedWith(Ios.class).to(AppleMarketPlace.class).in(Scopes.SINGLETON);bind(MarketPlace.class).annotatedWith(Android.class).to(GoogleMarketPlace.class).in(Scopes.SINGLETON);bind(MarketPlaceUser.class).in(Scopes.SINGLETON);}
} 现在如果MarketPlaceUser需要使用一个或另一个实现则可以通过以下方式注入依赖项 import com.google.inject.*;class MarketPlaceUser {private final MarketPlace marketPlace;Injectpublic MarketPlaceUser(Ios MarketPlace marketPlace) {this.marketPlace marketPlace;}} 这是非常直观的。 如果您担心定义太多注释另一种方法可能是使用Named内置的Google Guice注释方法是 class MultipleInstancesModule extends AbstractModule {Overrideprotected void configure() {bind(MarketPlace.class).annotatedWith(Names.named(ios)).to(AppleMarketPlace.class).in(Scopes.SINGLETON);bind(MarketPlace.class).annotatedWith(Names.named(android)).to(GoogleMarketPlace.class).in(Scopes.SINGLETON);bind(MarketPlaceUser.class).in(Scopes.SINGLETON);}
} 并在需要依赖的地方以这种方式使用它 import com.google.inject.*;class MarketPlaceUser {private final MarketPlace marketPlace;Injectpublic MarketPlaceUser(Named(ios) MarketPlace marketPlace) {this.marketPlace marketPlace;}} 如果您有兴趣进一步探索这里是Google guice示例和使用Spring框架的等效示例 翻译自: https://www.javacodegeeks.com/2015/02/disambiguating-between-instances-with-google-guice.html
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/86729.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!