@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestLog {
}
@Slf4j
@Aspect
@Component
public class RequestLogAspect {
@Around(“@within(org.springframework.stereotype.Controller) || @within(org.springframework.web.bind.annotation.RestController))”)
public Object aroundApi(ProceedingJoinPoint joinPoint) throws Throwable {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature)signature;
Method targetMethod = methodSignature.getMethod();
if(!targetMethod.isAnnotationPresent(RequestLog.class)) {
return joinPoint.proceed();
}
HttpServletRequest request = WebUtil.getRequest();
log.info(“{} : {}”, request.getRequestURI(), JSON.toJSONString(parseArgs(targetMethod, joinPoint.getArgs())));
return joinPoint.proceed();
}
public List parseArgs(Method method, Object[] args) {
Map<String, Object> paraMap = new HashMap<>(16);
Object requestBodyValue = null;
List reqArgs = Lists.newArrayList();
if (!paraMap.isEmpty()) {
reqArgs.add(paraMap);
}
if (requestBodyValue != null) {
reqArgs.add(requestBodyValue);
}
return reqArgs;
}
}
@Aspect
@Component
public class LogAspect {
/**
- 定义切入点,切入点为 spring.aop.ProductController 类下的所有方法
/
@Pointcut("execution(public * spring.aop.ProductController.(…))“)
public void log() {
}
/** - 前置通知:在连接点方法执行之前执行
/
@Before(“log()”)
public void doBefore(JoinPoint joinPoint) {
System.out.println((“-------------------- 前置通知逻辑 --------------------”));
}
/* - 后置通知:在连接点方法执行之后执行,即使连接点方法发生异常也会执行
/
//@After(“log()”)
public void doAfter() {
System.out.println(“-------------------- 后置通知逻辑 --------------------”);
}
/* - 返回通知:在连接点方法返回结果后执行,即连接点方法若发生异常则不会执行
- str为方法返回值的引用,参数名称可以自定义
/
//@AfterReturning(pointcut = “log()”, returning = “str”)
public void doAfterReturning(Object str) {
System.out.println(“返回通知逻辑…” + str);
}
/* - 异常通知:在连接点方法发生异常之后执行
/
//@AfterThrowing(“log()”)
public void doAfterThrowing() {
System.out.println(“异常通知逻辑…”);
}
/* - 环绕通知:在连接点方法执行之前和执行之后执行
*/
//@Around(value = “log()”)
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) { // 其它通知类型的方法也可以加上形参 ProceedingJoinPoint proceedingJoinPoint
System.out.println(”-------------------- 环绕通知执行开始 --------------------“);
Object result = null;
//获取方法所需参数
Object[] args = proceedingJoinPoint.getArgs();
System.out.println(“aaa…”);
try {
result = proceedingJoinPoint.proceed(args);
System.out.println(“bbb…”);
} catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println(“ccc…”);
}finally {
System.out.println(“result : {} " + result);
System.out.println(“ddd…”);
}
System.out.println(”-------------------- 环绕通知执行结束 --------------------”);
// 返回结果,此处可改变方法的返回结果
//return result;
return null;
}
}
@Component
public class ProductController {
public String save() {
System.out.println(“保存产品信息”);
//int i = 1/0;
return “hello”;
}
}