[英]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. 我想编写可以在运行时注入的通用验证器对象,选择一个具体的类型bean来验证但我无法使注入工作。 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: 然后我实现了一个带有String引用的具体类,如下所示:
@Override
public String getConfigurationCode() {
return "GENERIC_PASSWORD";
}
@Override
public ErrorMessages validate(String toValidate) {
return null;
}
In a stateless ejb i've injected this way 在无状态ejb中,我以这种方式注入
@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. 但是在
getValidatorsByConfig Instance<GenericValidator<T>>
委托中是一个空集合,我不知道为什么。 What i'm missing? 我想念的是什么?
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 然后,实例注入将能够注入
GenericValidator
所有实现,然后您可以使用GenericValidator.getConfigurationCode
选择合适的类型,或使用Instance.select(TypeLiteral<MyConcreteType>{})
选择合适的具体类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.