将相同的接口绑定两次(Guice) [英] Binding the same interface twice (Guice)

查看:122
本文介绍了将相同的接口绑定两次(Guice)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课程(让我们称之为 X Y )同时实施 Parser 接口做(相对)CPU密集型操作,为某些语法构建解析器( X Y )。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆