@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Length {
/**
* 最小长度
* @return
*/
int min() default 1;
/**
* 最大长度
* @return
*/
int max() default 100;
}
@Slf4j
@Aspect
@Component
@Order(2)
public class LengthAspect {
// @Pointcut("@annotation(com.crossoverjie.cim.common.annotation.TxtLength)")
@Pointcut("execution(public * com.crossoverjie.cim.route.controller.*.*(..))")
public void doValid(){
log.info("LengthAspect -> do valid..");
}
//使用before,如果定义返回对象,不会阻止流程继续往下执行,自定义对象不起作用
//使用around,可以使用自定义返回对象,并阻止流程继续往下执行
@Around("doValid()")
public Object beforeMethod(ProceedingJoinPoint pjp) throws Throwable {
log.info("LengthAspect -> beforeMethod process..");
Object[] args = pjp.getArgs();
if(args == null||args.length == 0){
//不是每个接口都需要检查返回错误
return pjp.proceed();
}
Field[] fields = args[0].getClass().getDeclaredFields();
for(int j=0; j<fields.length; j++){
TxtLength length = fields[j].getAnnotation(TxtLength.class);
if (null == length){
continue;
}
//变量定义的最小 、最大长度
int min = length.min();
int max = length.max();
String filedName = fields[j].getName();
// 入参属性值
JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(args[0]));
String fieldValue = jsonObject.getString(filedName);
if (StringUtils.isNotBlank(fieldValue) && (fieldValue.length() > max || fieldValue.length() < min)){
log.error("LengthAspect -> {} length is out of range.",filedName);
// throw ExceptionEnum.PARAM_LENGTH_ERROR.getException();
return ResponseVo.failed(ExceptionEnum.PARAM_LENGTH_ERROR);
}
}
return pjp.proceed();
}
}
版权声明:本文为datszhang原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。