spring mvc和spring boot實現AOP
阿新 • • 發佈:2018-11-11
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>