简单介绍一下注解:
@Aspect: 将一个java类定义为切面类
@Pointcut:定义一个切入点(规则表达式)
根据需要在切入点不同位置的切入内容
@Before:在切入点开始处切入内容
@After:在切入点结尾处切入内容
@AfterReturning:在切入点
return之后切入内容(返回值回调,可以用来对处理返回值做一些加工处理)
@Around:在切入点前后切入内容,并自己控制何时执行切入点自身的内容
@AfterThrowing:用来处理当切入内容部分抛出异常之后的处理逻辑
代码实现:
@Component
@Aspect
public class LogAspect {
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(LogAspect.class);
@Pointcut("execution(public * com.springboot.aop_logging.controller.*.*(..)))")
public void logPointCut() {
}
@Before("logPointCut()")
public void doBefore(JoinPoint joinPoint) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 记录下请求内容
LOG.info("请求地址 : " + request.getRequestURI().toString());
LOG.info("HTTP METHOD : " + request.getMethod());
LOG.info("IP : " + request.getRemoteAddr());
LOG.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
+ joinPoint.getSignature().getName());
LOG.info("参数 : " + Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(returning = "ret"
, pointcut = "logPointCut()")
public void log(Object ret) {
LOG.info("返回值 : " + ret);
}
@Around("logPointCut()")
public Object doAround(ProceedingJoinPoint pjp) {
long startTime = System.currentTimeMillis();
Object ob = null;
try {
ob = pjp.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
LOG.info("耗时 : " + (System.currentTimeMillis() - startTime));
return ob;
}
}
运行结果: