aop實現vaild引數驗證返回錯誤資訊
阿新 • • 發佈:2018-12-08
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; }