Search code examples
javagenericsjakarta-eecdiqualifiers

Can't use qualifiers with interface that consist generics


Met situation when cdi with qualifier and generics doesn't work.

For example, i have interface like this:

public interface SomeInterface<T> {
   T someMethod(Set<T> set);
}

Its implementation (and several another implementations with another qualifiers):

@SomeQualifier
public class SomeClass implements SomeInterface<AnotherClass> {
    AnotherClass someMethod(Set<AnotherClass> set) {...some logic...}
}

And some qualifier like this:

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
public @interface SomeQualifier {}

So, when i inject its in some bean (singleton in my project) :

@Singleton
@Startup
public class SomeSingleton {
  @Inject
  @SomeQualifier
  SomeInterface instance;

  ..usage...
}

i got exception in deploy process like

Unsatisfied dependencies for type SomeInterface with qualifiers @SomeQualifier

But when i use all of that without using generics - all works fine!

Tried injecting like this:

@Inject
@SomeQualifier
SomeInterface<AnotherClass> instance;

Got same result.

Any idea how can i use inject with qualifiers and generics?


Solution

  • The reason your first approach doesn't work is because you are violating CDI spec assignability rules (the very first line). In short - injecting raw type only works for unbound/Object types.

    However, the second approach does work - I just verified in with Weld SE. E.g.:

    @Inject
    @SomeQualifier
    SomeInterface<AnotherClass> instance;
    

    I suppose you might have forgotten to recompile your code or something? Double check that because I am certain this works. That, or you have some other problem in the code.