【问题标题】:Dependency injection with Guice for several implementations of same interface使用 Guice 对同一接口的多个实现进行依赖注入
【发布时间】:2018-06-21 17:11:25
【问题描述】:

我想尝试在我的项目中使用 Guice,但遇到了简单(从我的角度来看)的问题。

假设我有接口

public interface TradeService {
        public boolean buy(Player player, ProductID productId);
}

它有几个实现与它的依赖关系:

 public CarsTradeService implements TradeService {
      //...implementation here...
    }

    public BoatsTradeService implements TradeService {
      //...implementation here...
    }

    public AirplanesTradeService implements TradeService {
      //...implementation here...
    }

我了解如何配置实现并为它们提供所需的依赖项 - 为此我需要创建 guice "modules",它看起来像

public class CarsTradeModule extends AbstractModule {
    @Override 
    protected void configure() {
     bind(TradeService.class).to(CarsTradeService.class).in(Singleton.class);
    }
}

和类似的模块来休息两个服务。好的,模块已构建。但后来,当我需要将此实现注入某个类时 - 我如何才能注入完全需要的实现?

例如,如果我需要获取 CarsTradeService 的实例 - 我如何才能准确地获取此实例?

【问题讨论】:

  • 你尝试了什么,什么没用?

标签: java dependency-injection guice


【解决方案1】:

您可以使用 annotatedWith 和 @Named 来做到这一点。

bind(TradeService.class).annotatedWith(Names.named("carsTradeService")).to(CarsTradeService.class).in(Singleton.class);

在你想要注入这个bean的类中你需要使用

@Inject
@Named("carsTradeService")
private TradeService tradeService;

这将注入您需要的确切类。

【讨论】:

  • 谢谢,这似乎是一个解决方案。但是如果我需要将我的 TradeService 注入到不是由 Guice 创建的类的实例中怎么办?我将需要直接调用类似“injector.getInstance(TradeService.class)”的东西在这种情况下如何获得准确的实现?
【解决方案2】:

您可以使用 guice 多重绑定。这是一个guice扩展。

https://github.com/google/guice/wiki/Multibindings

@Override
public void configure() {
  Multibinder.newSetBinder(binder(),TradeService.class)
  .addBinding()
  .to(CarsTradeService.class);

  Multibinder.newSetBinder(binder(),TradeService.class)
  .addBinding()
  .to(BoatsTradeService.class);

  Multibinder.newSetBinder(binder(),TradeService.class)
  .addBinding()
  .to(AirplanesTradeService.class);
}

【讨论】:

  • 谢谢,这很有趣!我怎样才能在课堂上获得不是 Guice 创建的 TradeService 的确切实例?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-09
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多