aop实现vaild参数验证返回错误信息

public class UserInfo {
    @NotNull(message = "年龄不能为空",groups = Add.class)
    private String name;
    @Max(value = 100,message = "不能超过100")
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
     @GetMapping("add")
    public Object add(@Validated(Add.class) UserInfo userInfo, BindingResult result) {
        Map m = new HashMap<>();
        m.put("user", userInfo);
        return m;
    }

正常情况我们是在方法中,判断BingingResult是否存在error,然后返回错误信息.但是这样每个方法都需要写比较麻烦....可以交给aop统一处理;

 @Around(value = "point()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //是否存在验证vailded注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Annotation[][] methodAnnotations = method.getParameterAnnotations();
        for (Annotation[] a : methodAnnotations) {
            for (Annotation aa : a) {
                Object[] args = joinPoint.getArgs();
                for (Object o : args) {
                    if (o instanceof BindingResult) {
                        BindingResult result = (BindingResult) o;
                        StringBuilder s = new StringBuilder();
                        if (result.hasErrors()) {
                            for (FieldError fieldError : result.getFieldErrors()) {
                                s.append(fieldError.getDefaultMessage()).append(",");
                            }
                            Map map = new HashMap<>();
                            map.put("code", 204);
                            map.put("message", s.toString().substring(0, s.toString().length() - 1));
                            return map;
                        }
                    }
                }
            }
        }
        Object proceed = joinPoint.proceed();
        return proceed;
    }

猜你喜欢

转载自blog.csdn.net/myth_g/article/details/82558088