前言:
网上一些朋友分享了关于hibernate-validator的使用方法,但是不是缺少关联库信息,就是提供的参考代码中缺少自定类。
希望我这一篇博客能够让你顺利的跑出预期的结果。
如果有错,可以给我留言。
英文好的朋友可以参考官网的getting started。
http://hibernate.org/validator/documentation/getting-started/
一、环境
hibernate-validator库必须运行的JDK版本为1.6及以上。
二、hibernate-validator库及依赖
classmate-1.3..jar
hibernate-validator-5.3..Final.jar
javax.el-2.2..jar
javax.el-api-2.2..jar
jboss-logging-3.3..Final.jar
validation-api-1.1..Final.jar
三、假设我们构造了一个Car类
public class Car { @NotNull
private String manufacturer; @NotNull
@Size(min = , max = )
private String licensePlate; @Min()
private int seatCount; public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
} public String getManufacturer() {
return manufacturer;
} public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
} public String getLicensePlate() {
return licensePlate;
} public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
} public int getSeatCount() {
return seatCount;
} public void setSeatCount(int seatCount) {
this.seatCount = seatCount;
} }
四、如何校验呢?我们看看这个测试类
public class CarTest { public static void main(String[] args) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Car car = new Car(null, "苏A999999", ); Set<ConstraintViolation<Car>> constraintViolations = validator.validate(car);
for (ConstraintViolation<Car> constraintViolation : constraintViolations)
System.out.println("错误:" + constraintViolation.getMessage());
}
}
五、结果如何?
十一月 , :: 下午 org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.3..Final
错误:不能为null
错误:最小不能小于2
六、真是简单易用!虽然这个库重复“发明”了*。
七、你注意到了吗?结果是自动国际化了的!