这里,一个类是另一个类的子类。因此,@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;
}
Ambiguous dependency: there are multiple beans that match the injection point
但是,应用程序编译并运行时,容器不会将其视为定义错误。是不是写法有问题?我怀疑不会,如果this answer to a different question是正确的,表明只有一个 Bean 类型包含父类(super class)。
注意:正如预期的那样,以下用法不会导致 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 {}
因此,当您注入(inject) Scope
bean(不带任何限定符)时,将选择已明确指定为默认值的 bean:
@Inject
private Scope scopeBean; // The @Default annotated, if any of a Scope implementation is used.
关于java - 在 CDI 中使用 @Typed 的子类实现出现不明确的依赖警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38580395/