两次绑定相同的接口(Guice)

Binding the same interface twice (Guice)

我的 类(我们称它们为 XY)都实现了 Parser 接口(相对)做 CPU 密集操作来构建解析器某些语法(XY 的不同语法)。

现在我想将 XY 的(使用 Guice)依赖项注入到(上层)解析器 P 的构造函数中。 P 的两个参数都应该是 Parser:

类型
class P implements Parser {

    @Inject
    public P(Parser x, Parser y) {
        // ...
    }

}

如何让 Guice 区分 P 的两个参数中的哪一个应该接收 XY

如你所见,XY应该注释为@Singleton(但这个注释似乎与问题无关)。

您需要像这样使用 Named 注释:

class P implements Parser {

    @Inject
    public P(@Named("x") Parser x, @Named("y") Parser y) {
        // ...
    }

}

在 Guice 配置中,将每个命名变量分配给自己的实现 class

bind(Parser.class)
        .annotatedWith(Names.named("x"))
        .to(ParserXImplementation.class);

bind(Parser.class)
        .annotatedWith(Names.named("y"))
        .to(ParserYImplementation.class);