1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.调用方法对入参进行校验(对校验的参数,在实体类中对应参数上面加上@NotNull)
private String validate(@Valid Object obj) {
Set<ConstraintViolation<@Valid Object>> validateSet = Validation.buildDefaultValidatorFactory()
.getValidator()
.validate(obj, new Class[0]);
if (!CollectionUtils.isEmpty(validateSet)) {
String messages = validateSet.stream()
.map(ConstraintViolation::getMessage)
.reduce((m1, m2) -> m1 + ";" + m2)
.orElse("参数输入有误!");
return messages;
}
return null;
}
3.对返回值判断,返回null说明验证通过,notnull说明有空值存在,返回的信息即为“参数输入有误!”