Venu
Venu

Reputation: 303

CDI Ambiguous resolution exception

I have three classes defined as below.

class A {
}

class B extends A{
}

class C extends A{
}

class D{
//Inject class A
}

I am injecting class A in class D. CDI is throwing Ambiguous resolution exception. what is the right way to solve this ? Appreciate your help.

Upvotes: 2

Views: 4472

Answers (2)

Antonin Stefanutti
Antonin Stefanutti

Reputation: 1071

The @Typed annotation enables restricting bean types so that you can write:

class A {
}

@Typed(B.class)
class B extends A {
}

@Typed(C.class)
class C extends A {
}

class D {
//Inject class A
}

In your deployment, beans types of the bean class B (resp. C) will be restricted to B and Object (resp. C and Object) so that there will only one bean whose bean types contain type A and the ambiguous resolution will be resolved.

Note that the @Typed annotation is available since CDI 1.0.

Upvotes: 7

Kennedy Oliveira
Kennedy Oliveira

Reputation: 2291

You can use Qualifiers, so your code would look like this:

@ClazzA
class A {
}

@ClazzB
class B extends A{
}

@ClassC
class C extends A{
}

and when you try to inject, you will do something like this:

@Inject @ClassA
A a;

Check the Weld Doc

Upvotes: 2

Related Questions