aop+自定义注解实现打印接口出入参数
1:自定义注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface MethodLog {
int type() default 0;
}
- 运行时注解
- 作用域为方法上
- 注解参数: 0:打印入参+返回结果 1: 只打印入参
2: aop实现拦截注解打印参数
@Aspect
@Component
@Slf4j
public class MethodLogAspect {
@Pointcut("@annotation(cn.ssk.model.annotation.MethodLog)")
public void pointCut(){}
@AfterReturning(value = "pointCut()",returning = "result")
public void afterReturn(JoinPoint joinPoint,Object result){
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
MethodLog annotation = method.getAnnotation(MethodLog.class);
if (Objects.isNull(annotation)){
return;
}
String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName();
log.error("方法名:"+methodName);
int type = annotation.type();
Object[] args = joinPoint.getArgs();
log.info("入参:");
log.info(JSON.toJSONString(args));
if (type == 0){
log.info("返回结果:");
log.info(JSON.toJSONString(result));
}
} catch (Exception e) {
log.error("MethodLogAspect.afterReturn error",e);
}
}
}
- AfterReturning: 在方法return之前进入此aop, 可拿到该方法参数, 返回值等信息
- 通过JoinPoint 可拿到方法名, 注解, 参数
- 最后打印到log日志系统中
测试
- 注解作用于service
- postman参数
- 服务器打印参数