Binding the same interface twice (Guice)

2019-08-16 14:14发布

问题:

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