Reputation: 407
I am trying to validate a method parameter using custom annotation, but annotation validator is not getting invoked.
The annotation
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = FieldValidator.class)
public @interface ValidField {
String message() default "Incorrect field.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
The FieldValidator
public class FieldValidator implements ConstraintValidator<ValidField, String> {
@Override
public void initialize(final ValidField arg0) {
}
@Override
public boolean isValid(final String field, final ConstraintValidatorContext context) {
System.out.println("Called annotations successfully - "+ field);
return false;
}
}
Testing through the main method
public void testAnnotation(@ValidField String q){
System.out.println("inside testAnnotation..");
}
/************************* TESTING ****************************/
public static void main(String[] args) {
Test test= new Test();
test.testAnnotation("sample");
Expected: Called annotations successfully - sample should be displayed in the console
Upvotes: 1
Views: 4119
Reputation: 407
Okay, It was a mistake testing it by the main method.
@Retention(RetentionPolicy.RUNTIME)
says annotation will be available at runtime.
It was tested successfully by the service call when the server is running.
Upvotes: 1