AOP切面编程 后置通知实现返回值的判空值处理(项目中使用)

超、凢脫俗 2022-05-25 07:40 127阅读 0赞

目的:因为根据平常的代码在service层根据返回值要做判断空值处理,抛对应的错误信息,得每个方法判断一次,比较麻烦。现在的处理方法是根据放回值类型判断是否list.class,是的话list.size()=0抛对应的错误信息,然后在判断是否int.class等,希望能给大家代理帮助。

平常的代码写法

  1. if(i==0){
  2. throw new AppcationException(ExceptionEnum.DELETEDATADEFEAIED);
  3. }

错误类的种类

  1. INSERTDATADEFEATED(1001,"数据插入失败,"),
  2. NOTFOUNTVALUE(1002,"找不到对应的值"),
  3. UPDATEDATADEFEAIED(1003,"更新数据失败"),
  4. DElETEDATADEFEAIED(1004,"更新数据失败");

现在的写法

注意:1.

  1. Class returnType = ((MethodSignature) signature).getReturnType();

Api地址:

http://www.eclipse.org/aspectj/doc/released/runtime-api/org/aspectj/lang/reflect/MethodSignature.html\#getReturnType()

70

获取返回值类型

2.先判断list.class,int.class然后看是否是get或select开头的。

因为正规的话select开头返回object,get开头返回list,由于大家把两个闹乱了 所以做了一下改造,测试通过。

  1. @Aspect
  2. @Component
  3. public class ExceptionInterceptor {
  4. protected Logger log = (Logger) Logger.getLogger(this.getClass());
  5. /**
  6. * select开头 返回值为object
  7. * get开头 返回值为list
  8. * updat 返回值为int
  9. * delete开头 返回值为int
  10. * insert 返回值为int
  11. */
  12. @AfterReturning(value = "execution(* com.lenovo.pcsd.bp.businesspartner.mapper.*.*(..))", returning = "result")
  13. @SuppressWarnings("unchecked")
  14. public void afterReturning(JoinPoint joinPoint, Object result) {
  15. Signature signature = joinPoint.getSignature();
  16. String methodName = signature.getName();
  17. String selectregex = "^select.*$";
  18. String getregex = "^get.*$";
  19. String updateregex = "^updat.*$";
  20. String deleteregex = "^delete.*$";
  21. String insertregex = "^insert.*$";
  22. Class returnType = ((MethodSignature) signature).getReturnType();
  23. Pattern selectp = Pattern.compile(selectregex);
  24. Pattern getp = Pattern.compile(getregex);
  25. Pattern updatp = Pattern.compile(updateregex);
  26. Pattern deletep = Pattern.compile(deleteregex);
  27. Pattern insertp = Pattern.compile(insertregex);
  28. if (returnType.equals(List.class)) {
  29. List<? extends Object> list = (ArrayList<T>) result;
  30. if (list.size() == 0) {
  31. throw new AppcationException(ExceptionEnum.NOTFOUNTVALUE);
  32. }
  33. } else if (returnType.equals(Integer.class)) {
  34. Integer taskList = (Integer) result;
  35. if (taskList == 0) {
  36. if (updatp.matcher(methodName).matches()) {
  37. throw new AppcationException(ExceptionEnum.UPDATEDATADEFEAIED);
  38. } else if (deletep.matcher(methodName).matches()) {
  39. throw new AppcationException(ExceptionEnum.DElETEDATADEFEAIED);
  40. } else if (insertp.matcher(methodName).matches()) {
  41. throw new AppcationException(ExceptionEnum.INSERTDATADEFEATED);
  42. }
  43. }
  44. } else {
  45. if (StringUtils.isEmpty(result)) {
  46. if (getp.matcher(methodName).matches() || selectp.matcher(methodName).matches()) {
  47. throw new AppcationException(ExceptionEnum.NOTFOUNTVALUE);
  48. }
  49. }
  50. }
  51. }
  52. }

发表评论

表情:
评论列表 (有 0 条评论,127人围观)

还没有评论,来说两句吧...

相关阅读