我尝试在类级别学习带有 bean 验证的 JSF 2.0,如下所示: -
实用程序
@Singleton
public class MyUtility {
public boolean isValid(final String input) {
return (input != null) || (!input.trim().equals(""));
}
}
约束注解
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.TYPE,
ElementType.ANNOTATION_TYPE,
ElementType.FIELD
})
@Constraint(validatedBy = Validator.class)
@Documented
public @interface Validatable {
String message() default "Validation is failure";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
约束验证器
public class Validator extends ConstraintValidator<Validatable, MyBean> {
//
//----> Try to inject the utility, but it cannot as null.
//
@Inject
private MyUtility myUtil;
public void initialize(ValidatableconstraintAnnotation) {
//nothing
}
public boolean isValid(final MyBean myBean,
final ConstraintValidatorContext constraintContext) {
if (myBean == null) {
return true;
}
//
//----> Null pointer exception here.
//
return this.myUtil.isValid(myBean.getName());
}
}
数据 bean
@Validatable
public class MyBean {
private String name;
//Getter and Setter here
}
JSF 支持 bean
@Named
@SessionScoped
public class Page1 {
//javax.validation.Validator
@Inject
private Validator validator;
@Inject
private MyBean myBean;
//Submit method
public void submit() {
Set<ConstraintViolation<Object>> violations =
this.validator.validate(this.myBean);
if (violations.size() > 0) {
//Handle error here.
}
}
}
运行后,我遇到了java.lang.NullPointerException
该行中名为“Validator”的类的异常return this.myUtil.isValid(myBean.getName());
。我了解 CDI 不会注入我的实用程序实例。如果我错了,请纠正我。
我不确定我做错了什么还是 bean 验证限制。你能帮忙解释一下吗?