spring aop配置
<aop:aspect id="dtoParamCheckAspect" ref="dtoParamCheckInterceptor">
<aop:pointcut id="dtoParamCheckPoint" expression="execution(* com.mogujie.service.mogu.server.facade..*.*(..))"/>
<aop:around method="process" pointcut-ref="dtoParamCheckPoint"/>
</aop:aspect>
拦截器
public class DtoParamCheckInterceptor {
/**
* 处理dto 参数校验类
* @param pjp
* @return
* @throws Throwable
*/
public Object process(ProceedingJoinPoint pjp) throws Throwable {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
DtoParamCheck dtoParamCheck = AnnotationUtils.findAnnotation(method, DtoParamCheck.class);
if(dtoParamCheck == null){
return pjp.proceed();
}
Object[] args = pjp.getArgs();
int[] needCheckIndexArray = dtoParamCheck.needCheckArgIndexs();
for(int index: needCheckIndexArray){
Object arg = args[index];
Set<ConstraintViolation<Object>> validate = DtoParamCheckValidator.getInstance().validate(arg);
if(validate.size() > 0){
StringBuilder sb = new StringBuilder();
Iterator<ConstraintViolation<Object>> iterator = validate.iterator();
while (iterator.hasNext()){
sb.append(iterator.next().getMessage()).append("; ");
}
return new Response(SystemConstantsEnum.PARAM_ERROR.getCode(), sb.toString());
}
}
return pjp.proceed();
}
}
声明注解
/**
* 检测dto 参数注解
* User: beiye
* Date: 16/3/29.
*/
@Target({METHOD})
@Retention(RUNTIME)
@Documented
public @interface DtoParamCheck {
/**
* 需要检查的参数下标
* @return
*/
int[] needCheckArgIndexs() default {0};
}
函数使用
@Override
@DtoParamCheck
public Response<Integer> queryBloggerTotalCount(QueryBloggerListReqDto queryBloggerListReqDto)
**dto声明
@Data
public class QueryParentUrlReqDto{
/**
* 站点id
*/
@Min(value = 1, message = "cityId 最小值为{value}")
private Long cityId;
/**
* 网站名
*/
@StrNotBlank(message = "siteName 不能为空字符串")
private String siteName;
/**
* 创建人Id
*/
@CollectionNotEmpty(message = "creatorIdList 不能为空")
private List<Long> creatorIdList;
@Min(value = 1,message = "pageSize 最小值为 {value}")
private Integer pageSize;
@Min(value = 1,message = "pageNum 最小值为 {value}")
private Integer pageNum;
}
网友评论