springboot自定义注解校验
有时候框架自带的验证规则不是很满意 ,或者就是不喜欢 ,有钱任性
那么就自定义入参校验
定义一个注解
package com.yirui.supervisor.util;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Constraint(validatedBy = IsNullClass.class)
public @interface IsNull {
// flag无效时的提示内容
String message() default "";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
定义一个规则类,规则持续改进中,目的 一个注解判断这个参数所有情况的空值
package com.yirui.supervisor.util;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.util.List;
public class IsNullClass implements ConstraintValidator<IsNull,Object> {
/**
* 初始化时操作
* @param flagValidator
*/
@Override
public void initialize(IsNull flagValidator) {
}
/**
* @param value 用户输入的值,如从前端传入的某个值
*/
@Override
public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
if(value==null){
return false;
}
if(value instanceof String){
return isNullString(value);
}
if(value instanceof List){
return isNullList(value);
}
return isNullObj(value);
}
private boolean isNullObj(Object value){
Field[] fields = value.getClass().getDeclaredFields();
for (Field e : fields) {
if (e.getAnnotation(IsNull.class) != null) {
try {
e.setAccessible(true);
Object o = e.get(value);
if(o==null){
return false;
}
if(o instanceof String){
return isNullString(o);
}
if(o instanceof List){
return isNullList(o);
}
}catch (Exception es){
System.out.println(es);
}
}
}
return true;
}
private boolean isNullString(Object value){
if(!value.toString().equalsIgnoreCase("null") && value.toString().trim().length() > 0){
return true;
}
return false;
}
private boolean isNullList(Object value){
List list = (List) value;
for(Object o:list){
if(o==null){
return false;
}
if(o instanceof String){
return isNullString(o);
}
if(o instanceof List){
return isNullList(o);
}
return isNullObj(o);
}
return true;
}
}
使用
@Data @Accessors(chain = true) public class TbJobDeleteVO extends UserVO implements Serializable { private static final long serialVersionUID = 1L; /** * 主键id */ @IsNull(message = "id不能为空")
@ApiModelProperty(value = "主键id") private List<String> id; }