Binding the same interface twice (Guice)

我与影子孤独终老i 提交于 2019-12-24 20:34:22

问题


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).

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) {
        // ...
    }

}

How can I make Guice to differentiate which of the two arguments of P shall receive X and Y?

As you understand, X and Y should be annotated @Singleton (but this note seems unrelated with the question).


回答1:


You need to use Named annotation like this:

class P implements Parser {

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

}

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);


来源:https://stackoverflow.com/questions/47838771/binding-the-same-interface-twice-guice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!