【问题标题】:Ambiguous dependency warning with subclass implementation using @Typed in CDI在 CDI 中使用 @Typed 实现子类实现的模棱两可的依赖警告
【发布时间】:2016-07-26 03:03:58
【问题描述】:

在这里,一个类是另一个类的子类。因此,@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 匹配 注入点

但是,应用程序编译并运行,容器没有将其视为定义错误。是不是写的方式有问题?如果this answer to a different question 是正确的,我怀疑不会表明只有一个bean 的bean 类型包含超类。

注意:正如预期的那样,以下用法不会导致 Intellij 检查警告。

public class B {
    @Inject UserScopeAllowIdEquals usaie;
}

【问题讨论】:

    标签: java intellij-idea cdi weld


    【解决方案1】:

    基于 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 将被选中:

    @Inject
    private Scope scopeBean; // The @Default annotated, if any of a Scope implementation is used.
    

    【讨论】:

    • 在将Default 限定符添加到UserScope 之后,我仍然在注入UserScope 的地方收到“不明确的依赖”警告。为避免混淆仅供参考,Scope 基类是抽象的,因此永远不会注入 Scope
    • @PatrickGarner 您实际上需要注入抽象类,而不是具体实现
    • 我需要注入 RoleScope、PermissionScope、AcademicYearScope、TransitionLogScope 等,每个数据库表一个范围类型。所有这些都扩展了范围。 UserScopeAllowIdEquals 是这群人中唯一的怪人,它扩展了 UserScope 而不是 Scope。
    • 我确定你扩展 Scope 的原因是因为所有这些不同的范围都提供了一个统一的接口来验证访问权限,例如Scope.hasScope(...),这样对api用户的使用是相当透明的。本质上,根据您可能试图达到的场景,我会让我的 api 用户执行以下操作:@Inject @ScopeContext(PERMISSION) Scope scope; @Inject @ScopeContext(ACADEMIC_YEAR) Scope scope
    • 除了我在扩展 UserScope 之后注入了 UserScope 之外,没有任何注入导致问题,因此将 @Typed 注释添加到 UserScopeAllowIdEquals 似乎是一种更简单的方法,并且有效,因为,我认为,根据the CDI spec. section 5.2.2, "Unsatisfied and ambiguous dependencies",模棱两可的依赖关系变得可以由容器解决。因此,虽然它是模棱两可的,但它是可以解决的,在我看来,IDE 不应该给出警告。
    猜你喜欢
    • 2018-01-07
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多