spring boot aop 配置 使用
阿新 • • 發佈:2018-12-09
1. 首先要把aop的依賴加進來 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> 2. 根據自己的需求,建立相關的切面 package com.example.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; 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; /** * Created by wuwf on 17/4/27. * 日誌切面 */ @Aspect @Component public class LogAspect { @Pointcut("execution(public * com.example.service.*.*(..))") public void webLog(){} @Before("webLog()") public void deBefore(JoinPoint joinPoint) throws Throwable { // 接收到請求,記錄請求內容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 記錄下請求內容 System.out.println("URL : " + request.getRequestURL().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()); System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs())); } @AfterReturning(returning = "ret", pointcut = "webLog()") public void doAfterReturning(Object ret) throws Throwable { // 處理完請求,返回內容 System.out.println("方法的返回值 : " + ret); } //後置異常通知 @AfterThrowing("webLog()") public void throwss(JoinPoint jp){ System.out.println("方法異常時執行....."); } //後置最終通知,final增強,不管是丟擲異常或者正常退出都會執行 @After("webLog()") public void after(JoinPoint jp){ System.out.println("方法最後執行....."); } //環繞通知,環繞增強,相當於MethodInterceptor @Around("webLog()") public Object arround(ProceedingJoinPoint pjp) { System.out.println("方法環繞start....."); try { Object o = pjp.proceed(); System.out.println("方法環繞proceed,結果是 :" + o); return o; } catch (Throwable e) { e.printStackTrace(); return null; } } }