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