两次绑定相同的接口(Guice)
Binding the same interface twice (Guice)
我的 类(我们称它们为 X
和 Y
)都实现了 Parser
接口(相对)做 CPU 密集操作来构建解析器某些语法(X
和 Y
的不同语法)。
现在我想将 X
和 Y
的(使用 Guice)依赖项注入到(上层)解析器 P
的构造函数中。 P
的两个参数都应该是 Parser
:
类型
class P implements Parser {
@Inject
public P(Parser x, Parser y) {
// ...
}
}
如何让 Guice 区分 P
的两个参数中的哪一个应该接收 X
和 Y
?
如你所见,X
和Y
应该注释为@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);
我的 类(我们称它们为 X
和 Y
)都实现了 Parser
接口(相对)做 CPU 密集操作来构建解析器某些语法(X
和 Y
的不同语法)。
现在我想将 X
和 Y
的(使用 Guice)依赖项注入到(上层)解析器 P
的构造函数中。 P
的两个参数都应该是 Parser
:
class P implements Parser {
@Inject
public P(Parser x, Parser y) {
// ...
}
}
如何让 Guice 区分 P
的两个参数中的哪一个应该接收 X
和 Y
?
如你所见,X
和Y
应该注释为@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);