版权声明:欢迎转载,请附上转载地址 https://blog.csdn.net/qq_20143059/article/details/82870477
spring boot实现AOP
首先建立切面类需要@Aspect,@Component注解
然后建立@Pointcut确定什么方法实现aop
@Pointcut("execution(* com.air_baocl.controller.selectApi.*(..))")
然后可以选择实现@Before(“logPointCut()”) @AfterReturning(“logPointCut()”) @AfterThrowing(“logPointCut()”) @after(“logPointCut()”) @around(“logPointCut()”)方法
代码如下:
@Aspect
@Component
public class WebLogAspect {
private static final Logger LOG = LoggerFactory.getLogger(WebLogAspect.class);
@Pointcut("execution(* com.air_baocl.controller.selectApi.*(..))")
//两个..代表所有子目录,最后括号里的两个..代表所有参数。
//意思是selectApi类下的所有方法都实现AOP
public void logPointCut() {
}
@Before("logPointCut()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
LOG.info("请求地址 : " + request.getRequestURL().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()")// returning的值和doAfterReturning的参数名一致
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
LOG.info("返回值 : " + ret);
}
@Around("logPointCut()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
Object ob = pjp.proceed();// ob 为方法的返回值
LOG.info("耗时 : " + (System.currentTimeMillis() - startTime));
return ob;
}
@AfterThrowing("logPointCut()")
public void afterThrowing()
{
System.out.println("校验token出现异常了......");
}
}
spring mvc实现AOP
spring boot默认开启了AOP,但是mvc中默认没有开启,需要手动开启。
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>