java - 在 CDI 中使用 @Typed 的子类实现出现不明确的依赖警告

标签 java intellij-idea cdi weld

这里,一个类是另一个类的子类。因此,@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/

相关文章:

Android Studio - 推断无效?

java - 以应用程序启动的 CDI bean

maven - 启动payara 5 遇到过

java - 在 Wildfly 的单例中注入(inject) @RequestScoped 变量

java - 滚动 logback 日志记录不起作用

java - Servlet 过滤器坚持认为没有响应文本

java - 打开 STS 时出现错误对话

Java 和 Selenium 显示 Google 搜索结果的最佳方式

java - 如何设置 IntelliJ IDEA 以重新部署已更改的资源?

jsp - IDEA 14 中的标准 Tomcat 库