欢迎访问 生活随笔!

生活随笔

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

编程问答

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

发布时间:2023/12/3 编程问答 41 豆豆
生活随笔 收集整理的这篇文章主要介绍了 使用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消除实例之间的歧义的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。