Sprawdzanie poprawności bean JSR 303 Rozszerzony ConstraintValidator nie może używać CDI
Próbowałem nauczyć się JSF 2.0 ze sprawdzaniem poprawności komponentu bean na poziomie klasy w następujący sposób: -
Narzędzie
<code>@Singleton public class MyUtility { public boolean isValid(final String input) { return (input != null) || (!input.trim().equals("")); } } </code>
Adnotacja ograniczenia
<code>@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 {}; } </code>
Walidator ograniczeń
<code>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()); } } </code>
Fasola danych
<code>@Validatable public class MyBean { private String name; //Getter and Setter here } </code>
Fasola bazowa JSF
<code>@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. } } } </code>
Po uruchomieniu stanąłem przed wyjątkiemjava.lang.NullPointerException
w klasie o nazwie „Validator” w liniireturn this.myUtil.isValid(myBean.getName());
. Rozumiem, że CDI nie wstrzykuje mojej instancji narzędzia. Proszę popraw mnie jeżeli się mylę.
Nie jestem pewien, czy robię coś złego lub jest to ograniczenie sprawdzania poprawności fasoli. Czy mógłbyś pomóc wyjaśnić dalej?