java - 使用 Guice 对同一接口(interface)的多个实现进行依赖注入(inject)

标签 java dependency-injection guice

我想尝试在我的项目中使用 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);
    }
}

还有类似的模块来休息两个服务。好的,模块已构建。但后来,当我需要将此实现注入(inject)到某个类时 - 我如何注入(inject)所需的实现?

例如,如果我需要获取 CarsTradeService 的实例 - 我怎样才能准确获取该实例?

最佳答案

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

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

在你想要注入(inject)这个bean的类中,你需要使用

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

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

关于java - 使用 Guice 对同一接口(interface)的多个实现进行依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50964006/

相关文章:

node.js - 在 NestJS 中模拟多个 TypeORM 存储库

java - Jersey 3 - 使用bindFactory配置绑定(bind)

Java Guice - 如何将整数值绑定(bind)到我的类/对象?

unit-testing - 如果我使用 Mockito,我什至需要 Guice 吗?

java - 确保数据有效还是防止数据无效?两个都?

Java正则表达式查找数字模式

java - 如何在 Servlet 2.4 版本的 init() 方法中获取 ContextPath

java - 非守护进程 fork /加入池

dependency-injection - 配置文件中映射正确时的 Unity Container ResolutionFailedException

java - 在不绑定(bind) Guice 的情况下