注解/自定义注解+Aop 日志解耦

1:@RestController注解+AOP

@Slf4j
@Aspect
@Component
public class ControllerLogAspect {

    @Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
    public void funcLog() {
    }

    @Around("funcLog()")
    public Object funcLogProcess(ProceedingJoinPoint point) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String url = request.getRequestURL().toString();

        Object objResp = point.proceed();

        log.info("url:{} --request:{} --response:{}", url, point.getArgs().length > 0 ? JsonUtil.of(point.getArgs()[0]) : "", JsonUtil.of(objResp));
        return objResp;
    }
}

2:自定义注解@MethodLog+AOP

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface MethodLog {
    boolean response() default true;
}
@Slf4j
@Aspect
@Component
public class MethodLogAspect {

    @Pointcut("@annotation(com.example.demo.common.annotation.MethodLog)")
    public void funcLog() {
    }

    @Around("funcLog()")
    public Object funcLogProcess(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        Object objResp = point.proceed();

        MethodLog methodLog = AnnotationUtils.findAnnotation(method, MethodLog.class);
        if (methodLog != null && methodLog.response()) {
            log.info("method:{} --args:{} --resp:{}", method.getName(), point.getArgs().length > 0 ? JsonUtil.of(point.getArgs()[0]) : "", JsonUtil.of(objResp));
        } else {
            log.info("method:{} --args:{}", method.getName(), point.getArgs().length > 0 ? JsonUtil.of(point.getArgs()[0]) : "");
        }
        return objResp;
    }
}

猜你喜欢

转载自www.cnblogs.com/xiao-xin-xin/p/11128192.html