mirror of
https://gitee.com/durcframework/SOP.git
synced 2025-08-11 21:57:56 +08:00
JSR-303支持嵌套校验
This commit is contained in:
@@ -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));
|
||||
}
|
||||
});
|
||||
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
|
||||
}
|
||||
|
||||
}
|
||||
|
Reference in New Issue
Block a user