普通Java项目使用Hibernate Validator进行数据校验参数校验 校验Bean
背景
最近有负责维护一个专门做对外数据接口的项目,由于接口数据需要加密,而且解密后的数据需要校验,手动ifelse判断非常繁琐,因此想使用hibernate validator在数据解密后手动进行校验。
依赖
需要使用以下几个依赖,这里我是用的是maven,如果没有使用maven可以手动下载jar包引入。
需要注意的一点是,如果你使用的是Jdk8,hibernate-validator不要使用7以上的版本。
以及,在某些情况下可能需要引入jboss-logging包(如果报错)
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.2.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml/classmate -->
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>1.5.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.el/javax.el-api -->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.web/el-impl -->
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>el-impl</artifactId>
<version>2.2</version>
</dependency>
实体类添加注解校验
如果需要对嵌套的实体类也进行校验,需要在属性上加上@Valid注解,比如下面的equipments
@Data
@Accessors(chain = true)
public class Gamer {
@NotBlank(message = "角色名称不能为空")
private String name;
@Range(min = 0, max = 1, message = "性别只能是0或1")
private Integer sex;
@Min(value = 1, message = "攻击力最低为1")
private Integer attack;
@Min(value = 1, message = "防御力最低为1")
private Integer defense;
@Valid
@Size(min = 1, message = "装备列表不能空")
private List<Equipment> equipments = new ArrayList<>();
}
@Data
@Accessors(chain = true)
public class Equipment {
@NotBlank(message = "装备名称不能为空")
private String name;
@NotNull(message = "装备类型不能为空")
private Integer equipmentType;
}
编写校验工具类
public class ValidationUtil {
// 如果只需要返回第一个校验失败的信息,需要将下面的failFast设置为true
private static Validator validator = Validation
.byProvider(HibernateValidator.class)
.configure()
.failFast(false)
.buildValidatorFactory()
.getValidator();
public static <T> void validate(T bean) {
Set<ConstraintViolation<T>> validate = validator.validate(bean);
Iterator<ConstraintViolation<T>> it = validate.iterator();
for (; it.hasNext(); ) {
ConstraintViolation<T> next = it.next();
System.out.println(next);
}
}
}
测试
编写测试类进行测试
public class ValidationUtilTest {
@Test
public void testValidate() {
Gamer gamer = new Gamer();
gamer.setName("小红帽");
gamer.setAttack(-1);
gamer.setDefense(10);
gamer.setSex(0);
Equipment equipment = new Equipment().setEquipmentType(1);
gamer.getEquipments().add(equipment);
ValidationUtil.validate(gamer);
}
}