我想在我的Spring Boot应用程序中具有自定义验证批注。我已经完成了与示例中所示相同的所有操作,但是并没有触发。我想念的是什么?这是代码
@Documented
@Constraint(validatedBy = ContactNumberValidator.class)
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ContactNumberConstraint {
String message() default "Invalid phone number";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
这里是验证器类
public class ContactNumberValidator implements ConstraintValidator<ContactNumberConstraint, String> {
@Override
public void initialize(ContactNumberConstraint contactNumber) {
}
@Override
public boolean isValid(String contactField, ConstraintValidatorContext cxt) {
System.out.println("Validating....");
return contactField != null && contactField.matches("[0-9]+")
&& (contactField.length() > 8) && (contactField.length() < 14);
}
}
这里是控制器方法
@GetMapping("doSomething")
public void doSomething(@ContactNumberConstraint String phone) {
System.out.println("Do something " + phone);
}
还添加了此依赖项,但不确定是否需要。
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
任何想法?
要使用ConstraintValidator作为请求参数,您需要做一些额外的事情:
@Validated
在配置类中添加MethodValidationPostProcessor bean:
@Configuration
public class SpringConfiguration {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
}