Specifying different subclass implementations in CDI

丶灬走出姿态 提交于 2020-01-04 15:32:15

问题


I have two classes, A and B, which need to use a service. There are two services, S1 and S2. S2 extends S1. I wish to inject S1 into class A and S2 into class B. How can I accomplish this in CDI?

public class S1 {}
public class S2 extends S1 {}

public class A {
    @Inject S1 service;  //Ambigious?  Could be S1 or S2?
}

public class B {
    @Inject S2 service;
}

回答1:


The @Typed annotation enables restricting bean types so that you can write:

public class S1 {}

@Typed(S2.class)
public class S2 extends S1 {}

public class A {
    @Inject S1 service;
}

public class B {
    @Inject S2 service;
}

In your deployment, beans types of the bean class S2 will be restricted to S2 and Object so that there will only one bean whose bean types contain type S1 and the ambiguous resolution will be resolved.

Note that the @Typed annotation is available since CDI 1.0.

You could rely on qualifiers as well though it is preferable to use qualifiers for functional semantic.



来源:https://stackoverflow.com/questions/29066891/specifying-different-subclass-implementations-in-cdi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!