下面列出了怎么用org.aspectj.lang.annotation.AfterReturning的API类实例代码及写法,或者点击链接到github查看源代码。
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) {
if (aopLogInterface != null) {
aopLogInterface.afterReturning(ret);
}
try {
if (ret == null) {
return;
}
// 处理完请求,返回内容
Boolean isLog = IS_LOG.get();
if (isLog != null && !isLog) {
return;
}
DefaultSystemLog.getLog().info(" :" + ret.toString());
} finally {
IS_LOG.remove();
}
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
LogMenthodName logMenthodName = method.getAnnotation(LogMenthodName.class);
String time = (System.currentTimeMillis() - startTime.get()) + "ms";
if (method.isAnnotationPresent(LogMenthodName.class)) {
String token = request.getHeader(AuthSign.token);
Long id = AuthSign.getUserId(token);
if (id != 0) {
logAdminAgent.setReturnParam(Arrays.asList(ret).toString());
logAdminAgent.setTime(time);
logAdminAgent.setOperatorId(id);
logAdminAgent.setOperatorPlatform(LogAdminAgentAppEnum.ANDROID_SYS.getSystem());
logAdminAgent.setLoginFacility(HttpRequestUtil.getSystemDevice(request));
logAdminAgentService.save(logAdminAgent);
}
}
// 处理完请求,返回内容
logger.info("返回内容: " + Arrays.asList(ret));
logger.info("耗时 : " + time);
startTime.remove();
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
if (logger.isInfoEnabled()) {
logger.debug("systemMode:"+systemMode);
if ("prod".equals(systemMode.trim().toLowerCase()) && ret instanceof String) {
String resp = ret.toString();
try {
int bodyindex =resp.indexOf("\"body\":");
if(bodyindex>0) {
int errorindex =resp.indexOf(",\"errorMessage\"");
resp = resp.substring(0, bodyindex)+"..."+(errorindex>0?resp.substring(errorindex):"");
}
logger.info("RESPONSE : " + resp);
} catch (Exception e) {
logger.info("RESPONSE : " + ret);
}
} else {
logger.info("RESPONSE : " + ret);
}
}
}
/**
* 切面 配置通知
*
* @param joinPoint 连接点
*/
@AfterReturning("logPointCut()")
public void saveSysLog(JoinPoint joinPoint) {
//从切面织入点处通过反射机制获取织入点处的方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//获取切入点所在的方法
Method method = signature.getMethod();
//获取请求的类名
String methodInfo = joinPoint.getTarget().getClass().getName()+"#" + method.getName();
//请求的参数
Object[] args = joinPoint.getArgs();
//将参数所在的数组转换成json
String params = JSON.toJSONString(args);
//TODO 根据需求进行日志处理 可调用service保存SysLog实体类到数据库
log.info("....logPointCut....{}", methodInfo);
}
/**
* Do after.
*
* @param joinPoint the join point
*/
@AfterReturning(pointcut = "validateAnnotation()")
public void doAfter(final JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
Object target = joinPoint.getTarget();
//得到拦截的方法
Method method = getMethodByClassAndName(target.getClass(), methodName);
Object[] objects = joinPoint.getArgs();
//方法的参数
assert method != null;
ValidateAnnotation annotation = (ValidateAnnotation) getAnnotationByMethod(method, ValidateAnnotation.class);
if (annotation != null) {
BindingResult bindingResult = null;
for (Object arg : objects) {
if (arg instanceof BindingResult) {
bindingResult = (BindingResult) arg;
}
}
if (bindingResult != null && bindingResult.hasErrors()) {
String errorInfo = bindingResult.getFieldError().getDefaultMessage();
throw new IllegalArgumentException(errorInfo);
}
}
}
@AfterReturning(pointcut = "ruleTemplateAspect()", returning = "object")
public void ruleTemplateAspectAfter(JoinPoint joinPoint, Object object) throws InvocationTargetException, IllegalAccessException {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String localeStr = request.getHeader("Content-Language");
if (object != null) {
replaceMessage(object, localeStr);
}
}
@AfterReturning(pointcut = "templateMidTableInputMetaAspect()", returning = "object")
public void templateMidTableInputMetaAspectAfter(JoinPoint joinPoint, Object object) throws InvocationTargetException, IllegalAccessException {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String localeStr = request.getHeader("Content-Language");
if (object != null) {
replaceMessage(object, localeStr);
}
}
@AfterReturning(pointcut = "templateOutputMetaAspect()", returning = "object")
public void templateOutputMetaAspectAfter(JoinPoint joinPoint, Object object) throws InvocationTargetException, IllegalAccessException {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String localeStr = request.getHeader("Content-Language");
if (object != null) {
replaceMessage(object, localeStr);
}
}
@AfterReturning(pointcut = "ruleAspect()", returning = "object")
public void ruleAspectAfter(JoinPoint joinPoint, Object object) throws InvocationTargetException, IllegalAccessException {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String localeStr = request.getHeader("Content-Language");
if (object != null) {
replaceMessage(object, localeStr);
}
}
/**
* Find and return the first AspectJ annotation on the given method
* (there <i>should</i> only be one anyway...)
*/
@SuppressWarnings("unchecked")
protected static AspectJAnnotation<?> findAspectJAnnotationOnMethod(Method method) {
Class<?>[] classesToLookFor = new Class<?>[] {
Before.class, Around.class, After.class, AfterReturning.class, AfterThrowing.class, Pointcut.class};
for (Class<?> c : classesToLookFor) {
AspectJAnnotation<?> foundAnnotation = findAnnotation(method, (Class<Annotation>) c);
if (foundAnnotation != null) {
return foundAnnotation;
}
}
return null;
}
@AfterReturning(returning="result", pointcut="log()")
public void doAfterReturning(JoinPoint joinPoint, R result) {
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = sra.getRequest();
// 下面两个数组中,参数值和参数名的个数和位置是一一对应的。
// 参数值
Object[] args = joinPoint.getArgs();
// 参数名
String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
// 异步存储日志
CompletableFuture.runAsync(new SaveLogThread(sendLogService, args, argNames,
ThreadLocalUtils.get(Constants.CURRENT_MAIL_FROM), request.getRemoteHost(),
result.getCode(), result.getMessage()), SAVE_LOG_EXECUTOR_SERVICE);
log.debug("方法返回值:" + result);
}
@AfterReturning(pointcut = "antiAttack()")
public void doAfterReturning() throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String key = SysConstant.ANTI_ATTACK_ + request.getSession().getId();
ValueOperations valueOperations = redisTemplate.opsForValue();
valueOperations.set(key, "send sms all too often", 1, TimeUnit.MINUTES);
log.info("处理耗时:" + (System.currentTimeMillis() - startTime.get()) + "ms");
log.info("↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑");
startTime.remove();
}
/**
* 在结束之后插入后台操作记录
*/
@AfterReturning(pointcut = "pointCut()", returning = "retValue")
public void insertSysOperateLog(JoinPoint joinPoint, Object retValue) {
if (retValue instanceof String || retValue instanceof ModelAndView) {
return;
}
String methodName = joinPoint.getSignature().getName().toLowerCase();
boolean match = Arrays.stream(LOG_METHOD_NAMES).anyMatch(methodName::contains);
if (match) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
taskExecutor.execute(()->{
HttpServletRequest request = requestAttributes.getRequest();
String uri = request.getRequestURI();
String classType = joinPoint.getTarget().getClass().getName();
String param = null;
Map<String, String[]> parameterMap = request.getParameterMap();
if(parameterMap != null && parameterMap.size()>0 ){
param = JSON.toJSONString(parameterMap);
}
String returnParam = null;
if(retValue!=null){
returnParam = JSON.toJSONString(retValue);
}
SysOperateLogModel operateLog = new SysOperateLogModel();
operateLog.setClassName(classType);
operateLog.setRequestUrl(uri);
operateLog.setRequestParam(param);
operateLog.setResponseParam(returnParam);
operateLog.setRequestMethod(methodName);
operateLog.setOperateId(UserUtil.getOperatorId());
operateLog.setOperateName(UserUtil.getOperatorFromSession().getUserName());
SysOperateLogMqModel model = new SysOperateLogMqModel(operateLog);
log.info("准备发送MQ消息,tag:{}", model.getTag());
RocketMqSendUtil.sendMq(Collections.singletonList(model));
});
}
}
/**
* 返回通知
*
* @param ret
* @throws Throwable
*/
@AfterReturning(returning = "ret", pointcut = "log()")
public void doAfterReturning(Object ret) {
//得到当前线程的log对象
ApiLogger apiLogger = logThreadLocal.get();
// 发布事件
publisher.publishEvent(new SysLogEvent(apiLogger));
//移除当前log实体
logThreadLocal.remove();
}
/**
* 返回通知
*
* @param ret
* @throws Throwable
*/
@AfterReturning(returning = "ret", pointcut = "log()")
public void doAfterReturning(Object ret) {
//得到当前线程的log对象
ApiLogger apiLogger = logThreadLocal.get();
// 发布事件
publisher.publishEvent(new SysLogEvent(apiLogger));
//移除当前log实体
logThreadLocal.remove();
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
LOGGER.info("RESPONSE : " + ret);
LOGGER.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
LOGGER.info("***************End API Request***************");
}
@AfterReturning(pointcut = "restEndPoints()", returning = "result")
public void logAfterReturn(JoinPoint joinPoint, Object result) {
log.info("Exiting Method: " + joinPoint.getSignature().getName());
if (log.isDebugEnabled()) {
try {
log.debug("Response: " + mapper.writeValueAsString(result));
}
catch (JsonProcessingException e) {
log.warn("An error occurred while attempting to write value as JSON: " + result.toString());
log.warn(e.getMessage(), e);
}
}
}
@AfterReturning(pointcut = "restEndPoints()", returning = "result")
public void logAfterReturn(JoinPoint joinPoint, Object result) {
log.info("Exiting Method: " + joinPoint.getSignature().getName());
if (log.isDebugEnabled()) {
try {
log.debug("Response: " + mapper.writeValueAsString(result));
}
catch (JsonProcessingException e) {
log.warn("An error occurred while attempting to write value as JSON: " + result.toString());
log.warn(e.getMessage(), e);
}
}
}
@AfterReturning(pointcut = "restEndPoints()", returning = "result")
public void logAfterReturn(JoinPoint joinPoint, Object result) {
log.info("Exiting Method: " + joinPoint.getSignature().getName());
if (log.isDebugEnabled()) {
try {
log.debug("Response: " + mapper.writeValueAsString(result));
}
catch (JsonProcessingException e) {
log.warn("An error occurred while attempting to write value as JSON: " + result.toString());
log.warn(e.getMessage(), e);
}
}
}
@AfterReturning(pointcut = "transfer() and args(source, dest, amount)", returning = "isTransferSucessful")
public void afterTransferReturns(JoinPoint joinPoint, Account source, Account dest, Double amount,
boolean isTransferSucessful) {
if (isTransferSucessful) {
LOGGER.info("Amount transferred successfully ");
// find remaining balance of source account
}
}
@AfterReturning(returning = "object", pointcut = "logPointCut()")
public void doAfterReturning(Object object) {
if (object != null) {
logger.info("response={}", JacksonUtil.toJson(object));
} else {
logger.info("response=");
}
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
LOGGER.info("RESPONSE : " + ret);
LOGGER.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
startTime.remove();//用完之后记得清除,不然可能导致内存泄露;
}
@AfterReturning("controllerAspect()")
public void afterReturn(JoinPoint joinPoint){
System.out.println("=====执行controller后置返回通知=====");
if(logger.isInfoEnabled()){
logger.info("afterReturn " + joinPoint);
}
}
@AfterReturning("aspect()")
public void afterReturn(JoinPoint joinPoint){
System.out.println("===========执行后置返回通知==============");
if(log.isInfoEnabled()){
log.info("afterReturn " + joinPoint);
}
}
@AfterReturning(value = "pointcut()", returning = "result")
public void doAfter(JoinPoint joinPoint, Object result) {
RequestMapping requestMapping = getRequestMapping(joinPoint);
if (!isSholdRecord(requestMapping)) {
return;
}
OperateRecord operateRecord = new OperateRecord();
operateRecord.setOperateTime(new Date());
Signature signature = joinPoint.getSignature();
operateRecord.setHandler(signature.getDeclaringType().getSimpleName() + "#" + signature.getName());
operateRecord.setOperator(userModule.getCurrentUserId());
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
// if (requestAttributes != null) {
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
// if (request != null) {
operateRecord.setUri(request.getRequestURI());
operateRecord.setHttpMethod(request.getMethod());
operateRecord.setIp(WebUtils.getIpAddr(request));
operateRecord.setQueryString(request.getQueryString());
// }
// }
try {
String HeadlerArgs = desensitizationArgs(request, joinPoint.getArgs());
operateRecord.setHeadlerArgs(objectMapper.writeValueAsString(HeadlerArgs));
} catch (Exception e) {
log.warn(e.getMessage(), e);
}
if (result instanceof ApiRes) {
ApiRes apiRes = (ApiRes) result;
operateRecord.setApiResCode(apiRes.getCode());
if (StringUtils.equals(apiRes.getCode(), ApiRes.CODE_SUCCESS)) {
operateRecord.setOperateState(OperateRecord.OPERATE_STATE_SCUUESSED);
}
}
operateAuditModule.recordOperate(operateRecord);
}
@AfterReturning(returning = "ret", pointcut = "wsLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
if (log.isInfoEnabled()) {
try {
log.info("Response from server : \n" + JsonUtil.objectToJsonString(ret));
} catch (Exception e) {
log.info("log http response Exception:\n ", e);
}
}
}
/**
* 使用@AfterReturning在切入点return内容之后切入内容(可以用来对处理返回值做一些加工处理)
*
* @author 梦境迷离
* @time 下午4:37:25.
*/
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
log.info("RESPONSE : " + ret);
log.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
}
@AfterReturning(value = "pointCut()", returning = "result")
public void withUserInfo(Object result) {
Map<String, Object> context = AppContext.get();
if (context != null && context.get(AuthConstant.USER_ID) != null) {
int userId = (int) context.get(AuthConstant.USER_ID);
if (result instanceof ResponseEntity) {
deal(result, userId);
} else if (result instanceof CompletableFuture) {
((CompletableFuture) result).thenAccept(e -> {
deal(e, userId);
});
}
}
}
@AfterReturning("logPointCut()")
public void log(JoinPoint joinPoint) {
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Object[] args = joinPoint.getArgs();
OperateLogInfo logInfo = new OperateLogInfo(method,args);
logBuffer.enqueue(logInfo);
} catch (Exception ex) {
log.error("操作日志记录失败:" + ex.getMessage());
}
}
@AfterReturning(pointcut="execution(* org.packt.aop.transaction.service.impl.EmployeeServiceImpl.readEmployees(..))", returning="emps")
public void detectNullEmps(JoinPoint joinPoint, List emps) {
logger.info("DetectNullsAspect.detectNullEmps() detected : " + joinPoint.getSignature().getName());
if(emps == null){
logger.info("DetectNullsAspect.safeReadEmps() passes : empty " + emps);
}else{
logger.info("DetectNullsAspect.safeReadEmps() passes : " + emps);
}
}