【项目笔记】AOP在项目中打日志的应用

1. 定义log注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
}

凡是被Log注解修饰的方法,都会打log

2. 定义切面和切点

其中切点要指定Log注解,打印方法执行前和方法执行后的log

@Component
@Slf4j
@Aspect
public class XXXAspect {
    @Autowired
    private HttpServletRequest request;

    @Pointcut("@annotation(cn.homecredit.itlp.member.voting.common.aspect.Log)")
    public void log() {
        //do nothing, log() as a pointcut
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        log.info("\n\tURL = {},\n\tMETHOD = {},\n\tIP = {},\n\tCLASS METHOD = {},\n\tARGS = {}",
                request.getRequestURL(),
                request.getMethod(), request.getRemoteAddr(),
                joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(),
                joinPoint.getArgs());
    }

    @AfterReturning(returning = "result", pointcut = "log()")
    public void doAfterReturning(HSResult result) {
        log.info(result.getData().toString());
    }
}

加油儿!

上一篇:12-spring声明式实现AOP


下一篇:一个简单的性能拦截器