JSR-303支持嵌套校验

pull/1/head
tanghc 5 years ago
parent 55c5d0cad9
commit 5d2318f72d
  1. 21
      sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/param/ServiceParamValidator.java
  2. 14
      sop-common/sop-service-common/src/test/java/com/gitee/sop/servercommon/ValidatorTest.java

@ -11,6 +11,7 @@ import org.springframework.util.ReflectionUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@ -57,23 +58,31 @@ public class ServiceParamValidator implements ParamValidator {
private List<Object> listObjectField(Object object) {
List<Object> ret = new ArrayList<>();
ReflectionUtils.doWithFields(object.getClass(), field -> {
if (isCustomPackage(field.getType())) {
ReflectionUtils.makeAccessible(field);
ret.add(field.get(object));
}
});
}, this::isMatchField);
return ret;
}
/**
* 字段类型所在package是否是自定义包
* @param fieldType 指定的类型
* 匹配校验字段
*
* 1. 不为基本类型
* 2. 不为java自带的类型
* 3. 不为枚举
* @param field field
* @return true是自定义的
*/
private boolean isCustomPackage(Class<?> fieldType) {
private boolean isMatchField(Field field) {
Class<?> fieldType = field.getType();
if (fieldType.isPrimitive()) {
return false;
}
Class<?> declaringClass = field.getDeclaringClass();
boolean isEnum = declaringClass == field.getType() && declaringClass.isEnum();
if (isEnum) {
return false;
}
Package aPackage = fieldType.getPackage();
if (aPackage == null) {
return false;

@ -31,8 +31,8 @@ public class ValidatorTest extends TestCase {
public void testField() {
Manager manager = new Manager("Jim", 22);
Store store = new Store("仓库A", manager);
Manager manager = new Manager("Jim", 22, Type.TWO);
Store store = new Store("仓库A", manager, Type.ONE);
Goods goods = new Goods("Apple", new BigDecimal(50000), store);
serviceParamValidator.validateBizParam(goods);
}
@ -75,6 +75,9 @@ public class ValidatorTest extends TestCase {
@NotNull(message = "管理员不能为空")
private Manager manager;
@NotNull(message = "Store.type不能为空")
private Type type;
}
@Data
@ -84,6 +87,13 @@ public class ValidatorTest extends TestCase {
private String name;
private int age;
@NotNull(message = "Manager.type不能为空")
private Type type;
}
enum Type {
ONE,TWO
}
}

Loading…
Cancel
Save