具有多个实现的Guice和接口 [英] Guice and interface that has multiple implementations

查看:141
本文介绍了具有多个实现的Guice和接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有接口Validator和这个接口的多个实现。如何使用Guice注入任何多个实现?现在我知道我可以使用以下代码注入一个,但它只允许一个实现:

If I have interface Validator and multiple implementations for this interface. How can I inject any of the multiple implementations with Guice? Now I know that I can use following code to inject one, but it allows only one implementation:

public class MyModule extends AbstractModule {
  @Override 
  protected void configure() {
    bind(Validator.class).to(OneOfMyValidators.class);
  }
}

我想做的是:

Validator v1 = injector.getInstance(Validator1.class);
Validator v2 = injector.getInstance(Validator2.class);

有可能吗?

推荐答案

简答:绑定注释。它们基本上是一种让依赖者提供指向特定实例或实现的提示的方式,而不需要依赖于完整的具体实现类。

Short answer: binding annotations. They're basically a way of letting the depender give a hint that points towards a particular instance or implementation without requiring a dependency on the full concrete implementation class.

请参阅:
https://github.com/google/guice/wiki/BindingAnnotations

例如,在模块中,您可以这样做:

For example, in the module, you might do:

bind(Validator.class).annotatedWith(ValidatorOne.class).to(OneOfMyValidators.class);
bind(Validator.class).annotatedWith(ValidatorTwo.class).to(SomeOtherValidator.class);

在你的构造函数中,你会这样做:

And in your constructor, you'd do:

@Inject
MyClass(@ValidatorOne Validator someValidator,
    @ValidatorTwo Validator otherValidator) {
  ...
}

直接从 Injector 获取带注释的值,你必须使用Guice Key 类,例如:

To get an annotated value straight from an Injector, you'll have to use the Guice Key class, like:

Validator v1 = injector.getInstance(Key.get(Validator.class, ValidatorOne.class));

在旁注中,绑定注释对于注入运行时常量非常有用。请参阅 bindConstant 的评论:

On a side note, binding annotations are very useful for injecting runtime constants. See the comments for bindConstant in:

https://google.github.io/guice/api-docs/latest/javadoc /index.html?com/google/inject/Binder.html

这篇关于具有多个实现的Guice和接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆