user2918640
user2918640

Reputation: 473

How to choose a specific bean implementation without using qualifier?

I am providing implementation of an injected service interface at runtime , through a producer in my app.

Recently, another implementation of the same service interface has been created by someone in a collaborating team and that class has been added in a jar I can not avoid in my application. This is therefore throwing ambiguous dependency exception which I can obviously solve through a CDI qualifier on my producer method and at injection point. I wanted to ask if there is any other way to avoid this overhead. Can I use my @Produces method as the default implementation to make container ignore the second implementation? I added @Default annotation along with @Produces annotation on the producer method to check if this solves the problem since every injection by default is annotated with @Default. But that didn't work.

Upvotes: 1

Views: 392

Answers (2)

John Ament
John Ament

Reputation: 11723

If you can't annotate the second implementation using @Vetoed, I would write a CDI extension that vetoes the class via ProcessAnnotatedType

private void vetoSecondImpl(@Observes ProcessAnnotatedType<YourSecondImpl> pat) {
    pat.veto();
}

Here's a reference from the spec: http://docs.jboss.org/cdi/spec/1.2/cdi-spec.html#init_events

Upvotes: 0

Ken Chan
Ken Chan

Reputation: 90427

You can have the following options to avoid the overhead to create a new qualifier for a new implementation.

  1. Use the built-in qualifier @Named which allows you specify an implementation by String. (But it does not use CDI type safe injection feature)

  2. Create one qualifier that has the enum attribute. Each enum value represents an implementation . Which implementation to be injected is specified by this enum attribute. (Injection is type safe. See this for an example)

Upvotes: 1

Related Questions