这里,一个类是另一个类的子类。因此,@Typed注释用于防止@Inject歧义。
@Dependent
public class UserScope extends Scope {}
@Dependent
@Typed(UserScopeAllowIdEquals.class) // Restrict bean type.
public class UserScopeAllowIdEquals extends UserScope {}
以下用法导致Intellij中出现检查警告:
public class A {
@Inject UserScope userScope;
}
不明确的依赖关系:有多个bean与注入点
但是,应用程序编译并运行,容器不会将其视为定义错误。它的书写方式有问题吗?如果对另一个问题的回答是正确的,我怀疑这并不能表明只有一个bean的bean类型包含超类。
注意:按照预期,以下用法不会导致Intellij检查警告。
public class B {
@Inject UserScopeAllowIdEquals usaie;
}
基于CDI,只要一个bean有多个实现,那么@Default
限定符就不再适用。
为此,您需要明确地告诉CDI您的定义中的哪个bean是默认bean。
@Dependent
@Default
public class UserScope extends Scope {}
@Dependent
@Typed(UserScopeAllowIdEquals.class) // Restrict bean type.
public class UserScopeAllowIdEquals extends UserScope {}
因此,当您在没有任何限定符的情况下注入Scope
bean时,将选择已明确指定为默认bean的bean:
@Inject
private Scope scopeBean; // The @Default annotated, if any of a Scope implementation is used.