Patrick Garner
Patrick Garner

Reputation: 3321

Ambiguous dependency warning with subclass implementation using @Typed in CDI

Here, one class is a subclass of the other. Hence, the @Typed annotation is used to prevent @Inject ambiguity.

@Dependent
public class UserScope extends Scope {}

@Dependent
@Typed(UserScopeAllowIdEquals.class) // Restrict bean type.
public class UserScopeAllowIdEquals extends UserScope {}

The following usage causes an inspection warning in Intellij:

public class A {
    @Inject UserScope userScope;
}

Ambiguous dependency: there are multiple beans that match the injection point

However, the application compiles and runs, the container not treating it as a definition error. Is there a problem with the way it's written? I suspect not, if this answer to a different question is correct, to indicate that there will only be one bean whose bean types contain the superclass.

NOTE: The following usage, as expected, does not cause an Intellij inspection warning.

public class B {
    @Inject UserScopeAllowIdEquals usaie;
}

Upvotes: 1

Views: 8943

Answers (1)

maress
maress

Reputation: 3533

Based on CDI, as long as there is more than one implementation of a bean, then the @Default qualifier no longer applies.

To go about this, you need to explicitly tell CDI which bean among your definitions, is the default bean.

@Dependent
@Default
public class UserScope extends Scope {}

@Dependent
@Typed(UserScopeAllowIdEquals.class) // Restrict bean type.
public class UserScopeAllowIdEquals extends UserScope {}

So when you do inject a Scope bean, without any qualifier, then the bean which has been explicitly specified to be the default will be selected:

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

Upvotes: 3

Related Questions