我想创建一个CDI bean的多个实例,并进一步根据限定符对接口的聚合树选择实现进行进一步的选择。
在以下示例中,我创建了两个带有限定符的Controller实例。控制器是核心库的一部分,在我们的案例中该库包含许多类。我希望能够根据限定符为两个不同的Controller选择存储库的不同实现。
我可以创建一个@Producer在两个存储库实现之间进行选择,但是我不知道如何确定要返回哪个实例。我无权访问在Controller的注入点指定的限定符,而只能访问存储库的注入点。
[目前,我们有两个Repository实现在不同的战争中,它们依赖于核心lib来解决问题,但我希望能够对此进行更改。
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;
}
我思考我了解您想要的。这行得通吗?
@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
}