Search code examples
javacdiinjectgeneric-type-argument

Java CDI instance inject on generic type


i want to write generic validator objects that can be injected runtime chosing a concrete type bean to valide but i can't get injection working. Here are the interfaces classes:

public interface GenericValidator<T> {

    String getConfigurationCode();

    ErrorMessages validate(T toValidate);
}

public class GenericValidatorConstructor<T>  {

    @Inject
    private Instance<GenericValidator<T>> delegators;

    public List<GenericValidator<T>> getValidatorsByConfig(String configCode) {
        List<GenericValidator<T>> result = new ArrayList<GenericValidator<T>>();
        for (GenericValidator<T> validator : delegators) {
            if (configCode != null && configCode.equals(validator.getConfigurationCode()) ) {
                result.add(validator);
            }
        }
        return result;
    }
}

then i've implemente a concrete class with a String reference like this:

@Override
public String getConfigurationCode() {
    return "GENERIC_PASSWORD";
}

@Override
public ErrorMessages validate(String toValidate) {
    return null;
}

In a stateless ejb i've injected this way

@Inject
private GenericValidatorConstructor<String> passwordValidatorConstructor;

and then invoked the method

passwordValidatorConstructor.getValidatorsByConfig("GENERIC_PASSWORD");

but inside the getValidatorsByConfig Instance<GenericValidator<T>> delegators is an empty collection and i don't know why. What i'm missing?


Solution

  • Replace

    @Inject  
    private Instance<GenericValidator<T>> delegators;
    

    with:

    @Any 
    @Inject 
    private Instance<GenericValidator<?>> delegators;
    

    Then the Instance injection will be able to inject all implementations of your GenericValidator, and then you can use GenericValidator.getConfigurationCode to select the appropriate type, or use Instance.select(TypeLiteral<MyConcreteType>{}) to select the appropriate concrete type