日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

使用Google Guice消除实例之间的歧义

發布時間:2023/12/3 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用Google Guice消除实例之间的歧义 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

如果接口有多個實現,則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

總結

以上是生活随笔為你收集整理的使用Google Guice消除实例之间的歧义的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。