Verify JSR 303 bean extended by ConstraintValidator cannot use CDI

I tried to learn JSF 2.0 using a bean of class level checking like this: -

Utility

@Singleton public class MyUtility { public boolean isValid(final String input) { return (input != null) || (!input.trim().equals("")); } } 

Constraint Annotations

 @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 {}; } 

Constraint validator

 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 data

 @Validatable public class MyBean { private String name; //Getter and Setter here } 

JSF bean support

 @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. } } } 

After starting, I encountered an exception like java.lang.NullPointerException in a class named "Validator" in the line return this.myUtil.isValid(myBean.getName()); . I understand that CDI does not enter my instance of the utility. Please correct me if I am wrong.

I'm not sure if I am doing something wrong or this is a bean restriction. Could you help explain further?

+2
source share
1 answer

Your right, the Hibernate Constraint Validator is not registered as a CDI-Bean by default (and although it cannot receive dependencies).

Just put the seam check module in your classpath and everything should work fine.

BTW: Learning the source code of the module is a great example of the elegance and simplicity of expanding CDI. It does not need more than a few dozen lines of code to go from CDI to sleeping validation ...

+5
source

Source: https://habr.com/ru/post/927735/


All Articles