将相同的接口绑定两次(Guice) [英] Binding the same interface twice (Guice)
问题描述
我的课程(让我们称之为 X
和 Y
)同时实施 Parser
接口做(相对)CPU密集型操作,为某些语法构建解析器( X
和 Y $ c $的不同语法c>)。
My classes (let call them X
and Y
) both implementing Parser
interface do (relatively) CPU intensive operations to build parsers for certain syntaxes (different syntaxes for X
and Y
).
现在我想注入(使用Guice) X
和<$ c $的依赖关系c> Y 进入(上层)解析器 P
的构造函数。 P
的两个参数都应为 Parser
类型:
Now I want to inject (with Guice) dependencies of both X
and Y
into constructor of an (upper level) parser P
. Both arguments of P
should be of the type Parser
:
class P implements Parser {
@Inject
public P(Parser x, Parser y) {
// ...
}
}
如何让Guice区分哪个 P
的两个参数应接收 X
和 Y
?
How can I make Guice to differentiate which of the two arguments of P
shall receive X
and Y
?
如您所知, X
和 Y
应该进行注释 @Singleton
(但本说明似乎与问题无关)。
As you understand, X
and Y
should be annotated @Singleton
(but this note seems unrelated with the question).
推荐答案
您需要使用命名注释这个:
class P implements Parser {
@Inject
public P(@Named("x") Parser x, @Named("y") Parser y) {
// ...
}
}
ig将每个命名变量分配给他自己的实现类
in Guice config assign every named variable to his own implementation class
bind(Parser.class)
.annotatedWith(Names.named("x"))
.to(ParserXImplementation.class);
bind(Parser.class)
.annotatedWith(Names.named("y"))
.to(ParserYImplementation.class);
这篇关于将相同的接口绑定两次(Guice)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!