【问题标题】:Binding the same interface twice (Guice)绑定同一个接口两次(Guice)
【发布时间】:2017-12-15 19:29:09
【问题描述】:

我的类(我们称它们为XY)都实现了Parser 接口(相对而言)为某些语法(XY 的不同语法)构建解析器进行(相对)CPU 密集型操作。

现在我想将XY 的依赖关系注入(使用Guice)到(上层)解析器P 的构造函数中。 P 的两个参数都应该是 Parser 类型:

class P implements Parser {

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

}

如何让 Guice 区分 P 的两个参数中的哪一个应接收 XY

如您所见,XY 应该注释为@Singleton(但此注释似乎与问题无关)。

【问题讨论】:

    标签: java class dependency-injection interface guice


    【解决方案1】:

    你需要像这样使用Named注解:

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

    在 Guice 配置中将每个命名变量分配给他自己的实现类

    bind(Parser.class)
            .annotatedWith(Names.named("x"))
            .to(ParserXImplementation.class);
    
    bind(Parser.class)
            .annotatedWith(Names.named("y"))
            .to(ParserYImplementation.class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-10
      • 2021-04-20
      • 1970-01-01
      相关资源
      最近更新 更多