【问题标题】:Qualifier spanning a aggregate tree跨越聚合树的限定符
【发布时间】:2020-05-25 11:30:03
【问题描述】:

我想创建一个 CDI bean 的多个实例,并进一步向下聚合树选择接口的实现,具体取决于限定符。

在以下示例中,我创建了两个带有限定符的 Controller 实例。控制器是核心库的一部分,在我们的例子中包含许多类。我希望能够根据限定符为两个不同的控制器选择不同的存储库实现。

我可以创建一个 @Producer 来在两个 Repository 实现之间进行选择,但我不知道如何确定要返回哪个实例。我无法访问在 Controller 的注入点指定的限定符,而只能访问 Repository 的注入点。

目前我们有两个存储库实现生活在不同的战争中,它们依赖于解决问题的核心库,但我希望能够改变它。

应用

class MyApplication {
    @Inject
    @Component("comp1")
    Controller controller1;

    @Inject
    @Component("comp2")
    Controller controller2;
}

@Component("comp1")
public class Comp1Repository implements Repository {

}

@Component("comp2")
public class Comp2Repository implements Repository {

}

核心库

public interface Repository {

}

public class Controller {
    @Inject
    Repository repository;
}

【问题讨论】:

    标签: java jakarta-ee cdi


    【解决方案1】:

    认为我明白你想要什么。这行得通吗?

    @Produces
    @Component("comp1")
    @Dependent // or whatever scope you need
    private Controller makeAppropriateController(@Component("comp1") final Repository comp1Repository) {
      return makeController(comp1Repository); // however you do it
    }
    
    @Produces
    @Component("comp2")
    @Dependent // or whatever scope you need
    private Controller makeAppropriateController(@Component("comp2") final Repository comp2Repository) {
      return makeController(comp2Repository); // however you do it
    }
    

    【讨论】:

    • 感谢您的回复。是的,这适用于这个例子,不幸的是我已经简化了这个例子。在实际情况下,Controller 和 Repository 之间可能存在任意数量的聚合 bean。
    猜你喜欢
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多