![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5SYwkDMmRTOklDNzcDZ1YTYzYjZ0EjN2E2NjNGMkFDZ48CX5d2bs92Yl1iclB3bsVmdlR2LcNWaw9CXt92Yu4GZjlGbh5yYjV3Lc9CX6MHc0RHaiojIsJye.png)
1.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出現異常了......");
}
}
2.spring mvc實作AOP
springboot預設開啟了AOP,但是mvc中預設沒有開啟,需要手動開啟。
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>