文档
简单使用首先,在pojo添加注解,hibernate-validator提供了很多内置的注解
public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int seatCount;
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
//getters and setters ...
}
制定message(el表达式)
@Size(
min = 2,
max = 14,
message = "The license plate '${validatedValue}' must be between {min} and {max} characters long"
)
spring集成
@Valid
最常见的使用方式是在controller层的bean前和@Valid注解配合使用
@POST
@CacheEvict(key = "#user.username")
public Response createUser(@Valid @UniqueAccount Account user) {
return CommonResponse.op(() -> service.createAccount(user));
}
编码暴露
public static自定义校验器String validate(T bean) { Validator validator = Validation.byProvider(Hibernatevalidator.class) .configure() // .addProperty( "hibernate.validator.fail_fast", "true" ) .buildValidatorFactory().getValidator(); Set > validate = validator.validate(bean); List listError = new ArrayList<>(); if (validate.size() > 0) { validate.forEach(tConstraintViolation -> listError.add(tConstraintViolation.getMessage())); return StringUtils.join(listError, ","); } return StringUtils.EMPTY; }
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE, TYPE_USE })
@Retention(RUNTIME)
@Constraint(validatedBy = CheckCasevalidator.class)
@documented
@Repeatable(List.class)
public @interface CheckCase {
String message() default "{org.hibernate.validator.referenceguide.chapter06.CheckCase." +
"message}";
Class>[] groups() default { };
Class extends Payload>[] payload() default { };
CaseMode value();
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Retention(RUNTIME)
@documented
@interface List {
CheckCase[] value();
}
}
定义约束器
public class CheckCasevalidator implements ConstraintValidator{ private CaseMode caseMode; @Override public void initialize(CheckCase constraintAnnotation) { this.caseMode = constraintAnnotation.value(); } @Override public boolean isValid(String object, ConstraintValidatorContext constraintContext) { if ( object == null ) { return true; } if ( caseMode == CaseMode.UPPER ) { return object.equals( object.toUpperCase() ); } else { return object.equals( object.toLowerCase() ); } } }
在field添加注解
@NotNull
@Size(min = 2, max = 14)
@CheckCase(CaseMode.UPPER)
private String licensePlate;



