spring 切面编程中获取具体方法的方法
工作中,使用环绕通知,用来捕获异常,然后通过获取方法的返回值,返回不同的数据给到调用方。
由于方法的返回值不同,我们处理异常时,也需要返回不同的格式。
这时,就需要获取具体方法了的返回值了。
我的环绕通知方法如下:
@Around(value = "GlobalControllerAspect.controllerPointcut()") public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { Object result = null; try { long statrTime=System.currentTimeMillis(); result = proceedingJoinPoint.proceed(); long endTime=System.currentTimeMillis(); String declaringTypeName = proceedingJoinPoint.getSignature().getDeclaringTypeName(); String methodName = proceedingJoinPoint.getSignature().getName(); StringBuilder spendTimeLog=new StringBuilder("方法名称:").append(declaringTypeName).append(".").append(methodName).append("() 耗时为:").append(endTime-statrTime).append("ms."); logger.info(spendTimeLog.toString()); } catch (Exception e) { logger.error("环绕通知捕获异常信息:",e); ResponseModel responseModel=new ResponseModel(); if (e instanceof RuntimeException) { responseModel.setStatus(ResponseModel.STATUS_FAIL); responseModel.setMsgType(ResponseModel.MSGTYPE_INFO); responseModel.setMsgContent(e.getMessage()); } else { responseModel.setMsgType(ResponseModel.MSGTYPE_WARINNING); responseModel.setStatus(ResponseModel.STATUS_ERROR); responseModel.setMsgContent(e.getMessage()); } Signature sig = proceedingJoinPoint.getSignature(); MethodSignature msig = null; if (!(sig instanceof MethodSignature)) { throw new IllegalArgumentException("该注解只能用于方法"); } msig = (MethodSignature) sig; Object target = proceedingJoinPoint.getTarget(); Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes()); Class<?> returnType = currentMethod.getReturnType(); if(returnType.isAssignableFrom(responseModel.getClass())||returnType==ResponseModel.class){ return responseModel; }else if(returnType==JSONObject.class){ return responseModel.toJSON(); } } return result; }
获取具体方法的代码:
Signature sig = proceedingJoinPoint.getSignature(); MethodSignature msig = null; if (!(sig instanceof MethodSignature)) { throw new IllegalArgumentException("该注解只能用于方法"); } msig = (MethodSignature) sig; Object target = proceedingJoinPoint.getTarget(); Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes()); Class<?> returnType = currentMethod.getReturnType();
获取到具体方法,返回值就很容易获取了。