在CDI中指定不同的子类实现

在CDI中指定不同的子类实现

问题描述:

我有两个类,A和B,需要使用服务。有两个服务,S1和S2。 S2扩展了S1。我希望将S1注入A类,将S2注入B类。如何在CDI中实现这一目标?

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;
}


@Typed 注释启用限制bean类型,以便您可以编写:

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;
}

在您的部署中, S2 的.org / cdi / spec / 1.2 / cdi-spec.html#bean_types rel = nofollow>豆类型 S2 Object ,这样将只有一个其类型为 S1 和歧义分辨率将得到解决。

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.

请注意,可以使用 @Typed 批注从CDI 1.0开始。

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

您也可以依赖于限定词,尽管最好将限定词用于 functional 语义。

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