使用注解实现入参参数校验
工作场景中,参数校验必不可少,最近利用自定义注解实现入参参数校验,在入参校验方面,有不错的扩展性,可重用性。
效果
接口调用,如果入参是实体类,就在实体类的变量上方标记。  实体类例子 
返回结果 
实现
先自定义一个注解,用来标记需要校验的参数。
@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Examine {
String value() default "isNull";
}
利用注解的标记,定义一个aop,实现对参数的获取和校验
@Component
@Aspect
public class ExamineAop {
@Around("@annotation(examine)")
public Object paramCheck(ProceedingJoinPoint joinPoint, Examine examine) throws Throwable {
Object[] args = joinPoint.getArgs();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Parameter[] parameters = signature.getMethod().getParameters();
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
if (isPrimite(parameter.getType())) {
Examine annotation = parameter.getAnnotation(Examine.class);
if (annotation == null) {
continue;
}
if (args[i] == null) {
throw new ExamineException();
}
Method verificationUtil = VerificationUtil.class.getMethod(annotation.value(), Object.class);
Object invoke = verificationUtil.invoke(null, args[i]);
if (invoke.equals(false)) {
throw new ExamineException();
}
continue;
}
Class<?> paramClazz = parameter.getType();
Object arg = Arrays.stream(args).filter(ar -> paramClazz.isAssignableFrom(ar.getClass())).findFirst().get();
Field[] declaredFields = paramClazz.getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
Examine annotation = field.getAnnotation(Examine.class);
if (annotation == null) {
continue;
}
if (args[i] == null) {
throw new ExamineException();
}
Method verificationUtil = VerificationUtil.class.getMethod(annotation.value(), Object.class);
Object invoke = verificationUtil.invoke(null, field.get(arg));
if (invoke.equals(false)) {
throw new ExamineException();
}
continue;
}
}
return joinPoint.proceed();
}
private boolean isPrimite(Class<?> clazz) {
return clazz.isPrimitive() || clazz == String.class;
}
}
验证工具类,在aop实现类中利用反射调用,在本类中可以添加自己的验证,在注解中,传入方法名字,即可调用方法来验证参数,如(Examine(isPhone)String phone)。
public class VerificationUtil {
public static Boolean isPhone(Object phone) {
String pattern = "^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\\d{8})?$";
return phone.toString().matches(pattern);
}
public static Boolean isNull(Object value) {
return value != null || String.valueOf(value).length() > 0;
}
}
结尾
在本程序中还有异常类和全局捕获异常没有写出,百度一大堆。 如有错误和bug,欢迎指正。
|