CDI。使用@Specializes

CDI. Using @Specializes

我有一个关于使用 @Specialization 的问题。按照 Java EE 6 或 7 教程的规定,如果我通过给它 @Specializes 注释来声明我的 bean,它将完全替换扩展我的 bean 的 bean。例如

    public interface I {}
    @Default @Q
    public class A implements I {}
    @Specializes
    public class SpecA extends A {}
    ////
    a) @Inject I a;
    b) @Inject @Q I b;

将 SpecA 注入字段 'a' 和 'b' 是否足够? 我尝试在 glassfish 4.0 上 运行 这个例子,但没有成功。

我在教程中看到奇怪的句子: 'Usually, a bean marked with the @Specializes annotation is also an alternative and is declared as an alternative in the beans.xml file. ' 我不明白我应该怎么做才能让它按照教程中的规定工作?我需要添加注释 @Alternative 并将此 class 添加到 beans.xml 吗?或者我需要将我的 bean 添加到 beans.xml 吗?

回答您的问题

Do I need add annotation @Alternative and add this class to beans.xml?

Do I need add my bean to beans.xml?

没有。以上即可

为您提供更多背景信息:

@Specializes 或多或少意味着专门化 @Alternative bean。

@Alternative bean 用于替换

时,

@Specializes 会派上用场

  • a bean/implementation 用一个或多个限定符注释 和
  • 注入点使用 one/more 限定符。

案例 1:您有一个没有限定符的 bean/implementation(我们调用 BeanA)。在这种情况下,您不需要 @Specializes,您将不得不

  1. 创建一个要使用的 @Alternative bean(我们称之为 AltBean) 作为 BeanA 的替代品
  2. 将 beans.xml 中的 AltBean 列为替代项

案例 2:您有一个 bean/implementation(在您的案例 A 中)有一个或多个限定符。在这种情况下你必须

  1. 创建一个@Alternative@Specializesbean (SpecA) 您想用作 A
  2. 的替代品
  3. 使SpecA扩展A
  4. 将 beans.xml 中的 SpecA 列为替代项

你的是案例 2。