import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.*; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; /** * @Description TODO * @Author * @Date 2019/4/2 15:29 **/ @Aspect @Component public class WebControllerAop { @Pointcut("execution(public * com.zhongda.yunxiao.phone.controller.*.*(..))") public void webLog(){ System.out.println("记录日志---------------------"); } @Before("webLog()") public void doBefore(JoinPoint joinPoint){ System.out.println("我是前置通知!!"); //获取目标方法的参数信息 Object[] args = joinPoint.getArgs(); Signature signature = joinPoint.getSignature();//签名 //代理的哪个方法 System.out.println("方法:"+signature.getName()); //Aop 代理类的名字 System.out.println("方法的包所在:"+signature.getDeclaringTypeName()); //Aop 代理类的信息 signature.getDeclaringType(); MethodSignature methodSignature = (MethodSignature) signature; String[] parameterNames = methodSignature.getParameterNames(); System.out.println("参数名:"+Arrays.toString(parameterNames)); System.out.println("参数值agrs:"+Arrays.toString(joinPoint.getArgs())); // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //记录下请求的内容 System.out.println("请求Url:"+request.getRequestURI().toString()); System.out.println("HTTP_METHOD:"+request.getMethod()); System.out.println("IP :"+request.getRemoteAddr()); System.out.println("CLASS_METHOD:"+joinPoint.getSignature().getDeclaringTypeName()+","+ joinPoint.getSignature().getName()); } /** *@Author *@Description //TODO 处理完请求返回内容 *@Date 15:54 2019/4/2 *@return void **/ @AfterReturning(returning = "ret",pointcut = "webLog()") public void doAfterReturning(Object ret) throws Throwable{ System.out.println("方法的返回值:"+ret); } /** *@Author *@Description //TODO 后置异常通知 *@Date 15:57 2019/4/2 *@return void **/ @AfterThrowing("webLog()") public void thorwss(JoinPoint jp){ System.out.println("方法异常时执行....."); } /** *@Author *@Description //TODO 后置最终通知,final增强,不管是抛出异常或者正常退出都会执行 *@Date 15:58 2019/4/2 *@return void **/ @After("webLog()") public void after(JoinPoint jp){ } /** *@Author *@Description //TODO 环绕通知,环绕增强,相当于MethodInterceptor *@Date 15:59 2019/4/2 *@return java.lang.Object **/ @Around("webLog()") public Object arround(ProceedingJoinPoint pjp) { try { Object o = pjp.proceed(); return o; } catch (Throwable e) { e.printStackTrace(); return null; } } }
springboot Aop
最新推荐文章于 2022-12-06 08:28:29 发布