guice 实例_使用Google Guice消除实例之间的歧义
guice 實例
如果接口有多個實現,則Google guice提供了一種精巧的方法來選擇目標實現。 我的示例基于Josh Long ( @starbuxman )的出色文章,內容涉及Spring提供的類似機制。
因此,請考慮一個名為MarketPlace的接口,該接口具有兩個實現,分別是AndroidMarketPlace和AppleMarketPlace:
并考慮以下實現的用戶:
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
guice 實例
總結
以上是生活随笔為你收集整理的guice 实例_使用Google Guice消除实例之间的歧义的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何有效防御ddos攻击(怎样防范ddo
- 下一篇: JAVA环境变量(java环境linux